I'm blocked since few hours now, I wish somebody can help me figure out what I do wrong.
This whole code is to get a json response from an API. I want to understand what are my errors, so please, explain a little ! ;)
const fetch = require('node-fetch');
const Bluebird = require('bluebird');
fetch.Promise = Bluebird;
const xml2js = require('xml2js');
module.exports = {
getImage : async function (tag, random){
let url = "anApiLink" + tag;
if(random != null) url = "anApiLink" + tag + "&id=" + random;
const get_data = async url => {
try {
const response = await fetch(url);
if(! response.ok) return new Error("Erreur lors de la récupération de l'image : " + response.statusText);
const text = await response.text();
const xmlToJson = await xml2js.parseString(text, (err, result) => {
if(err) throw err;
const json = JSON.stringify(result, null, 4);
return json;
});
console.log(xmlToJson);
return xmlToJson;
} catch (err) {
console.error(err);
}
};
return get_data(url);
}
}
My json const is what I want to return from the global function (get_data), and it's an actual good json answer. With my final return, I actually get what's below.
From my console.log() :
{
comment: '',
sgmlDecl: '',
textNode: '',
tagName: '',
doctype: '',
procInstName: '',
procInstBody: '',
entity: '',
attribName: '',
attribValue: '',
cdata: '',
script: '',
c: '',
q: '',
bufferCheckPosition: 65536,
opt: { trim: false, normalize: false, xmlns: false, lowercase: undefined },
looseCase: 'toUpperCase',
tags: [],
sawRoot: false,
closedRoot: false,
closed: false,
error: null,
tag: null,
strict: true,
noscript: true,
state: 0,
strictEntities: undefined,
ENTITIES: {},
attribList: [],
trackPosition: true,
column: 0,
line: 0,
position: 0,
errThrown: false,
onerror: [Function],
onend: [Function],
ended: true,
onopentag: [Function],
onclosetag: [Function],
ontext: [Function],
oncdata: [Function],
startTagPosition: 781
}
Thanks for the help.
Salut, I didn't even realize at first that I was reading french in your code... Your problem seemed to be related to that library you're using, xml2js. I took a look at their docs, and maybe this may help you.
The function itself does not return the result, but you can get it in the callback, that's the reason why you're logging this weird object. You could create a separate var to store the result, but I have a better solution.
If you want to use promises, I found this in the docs, and this in the source code about parseStringPromise, and I think that's what you want. The source code indicates that the result is returned as a Promise here.
In short, what you return in the callback isn't returned by parseString. This is what xmlToJson should be to act as intended.
// Not tested. I might have made an error about the location of 'then', not sure.
const xmlToJson = await xml2js.parseStringPromise(text)
.catch(e => throw e)
.then(r => JSON.stringify(r, null, 4))
I want to store below object into my localstorage and want to use throughout application. For that I used circular function. But when I recreate object from string then it is not same object. Below is my object.
e.exports {client: I}
client: I
browserDetails: {browser: "chrome", version: 80}
permOnClick: true
ringToneFlag: true
ringToneBackFlag: true
connectToneFlag: true
isLoggedIn: true
reconnectInterval: null
reconnectTryCount: 0
localStorage: Storage
length: 13
AsteriskIntegration:ServerIP: ""
auto_saved_sql: "INSERT INTO document_revisions (id,change_log,document_id,doc_id,doc_type,doc_url,date_entered,created_by,filename,file_ext,file_mime_type,revision,deleted,date_modified) VALUES ('e0a40e04-ceb6-dd54-a05d-5e5cc8f4461b','Document Created','390d0e08-1ba9-dcff-1eb8-5e5cc8b83741','','Sugar','','2020-03-02 08:47:40','1','Test.pdf','pdf','application/pdf','1',0,'2020-03-02 08:47:40')"
plivoBrowserSdkJSON: "{"client":{"browserDetails":{"browser":"chrome","version":80},"permOnClick":true,"ringToneFlag":true,"ringToneBackFlag":true,"connectToneFlag":true,"isLoggedIn":true,"reconnectInterval":null,"reconnectTryCount":0,"localStorage":{"AsteriskIntegration:ServerIP":"","endpointID":"001f922acfecfd9498ea0b2b84703ce8f14d2fa55dc96b857bfbfd1ffe9af40d","AsteriskIntegration:Extension":"","AsteriskIntegration:Context":"","AsteriskIntegration:ToggleStatus":"Minimized","AsteriskIntegration:ShowNotification":"0","favorite_tables":"undefined","debug":"","csio_auth_data":"\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWJtaXNzaW9uSW50ZXJ2YWwiOiI1MDAwIiwic2NvcGUiOlsicmVzdC1hcGktaDEiLCJyZXN0LWFwaSIsInN0b3JlLXNkcCIsImh0dHBzOi8vZXZlbnRzLWV1LXdlc3QtMS5jYWxsc3RhdHMuaW8vdjEvYXBwcyIsImh0dHBzOi8vc3RhdHMtZXUtd2VzdC0xLmNhbGxzdGF0cy5pby92MS9hcHBzIiwiaHR0cHM6Ly9hcHBzZXR0aW5ncy1ldS13ZXN0LTEuY2FsbHN0YXRzLmlvL3YxL2FwcHMiLCJodHRwczovL2Rhc2hib2FyZC1ldS13ZXN0LTEuY2FsbHN0YXRzLmlvL2FwcHMiXSwiY29sbGVjdFNEUCI6dHJ1ZSwiYWRhcHRpdmVJbnRlcnZhbCI6ZmFsc2UsImFkYXB0aXZlU3RhdHNFbmFibGVkIjpmYWxzZSwibXVsdGlTRFAiOmZhbHNlLCJ0YWFzRW5hYmxlZCI6ZmFsc2UsInJhd1VzZXJJRCI6ImRhdmlkNTcxOTg5ODM1ODMyOTU0OTIzMSIsInVzZXJJRCI6ImRhdmlkNTcxOTg5ODM1ODMyOTU0OTIzMSIsImp3dGlkQ2hhaW4iOlsiNDIiXSwiZW5kcG9pbnRUeXBlIjoiY2xpZW50IiwiYXBwSUQiOjM4MDA3NzA4NCwicmVzdEFwaVRyYW5zcG9ydCI6dHJ1ZSwicmVuZXdJbnRlcnZhbCI6MzQwMDAwMCwiZXhwaXJ5IjoiMjAyMC0wMi0xM1QwNzoxMDo1MS4zMDZaIiwib3JpZ2luIjpudWxsLCJpYXQiOjE1ODE1NzQ0NTEsImV4cCI6MTU4MTU3ODA1MSwianRpIjoiZWYxYmIxN2YtYzFkNy00MjJlLTg0MDktNTBmODQ4YjJhMmI4In0.FsF6rn82ss9JcAC9UxqUFeCiTe0xl9WDNNeQHBoFc4s\"","AsteriskIntegration:UserID":"1","AsteriskIntegration:SocketPort":""},"_events":{},"_eventsCount":0,"phone":{"_events":{},"_eventsCount":7,"_cache":{"credentials":{}},"_configuration":{"authorization_user":"david","password":null,"realm":"phone.plivo.com","ha1":"2291bb7891ceefc3ab2221cb1565fba6","display_name":null,"uri":{"_parameters":{},"_headers":{},"_scheme":"sip","_user":"david5719898358329549231","_host":"phone.plivo.com"},"contact_uri":{"_parameters":{"transport":"ws"},"_headers":{},"_scheme":"sip","_user":"r594n4dv","_host":"aeqf7b88emss.invalid","_port":null},"instance_id":"78fdf100-2c4d-4deb-a8ac-0cee371db730","use_preloaded_route":false,"session_timers":false,"session_timers_refresh_method":"UPDATE","no_answer_timeout":60000,"register":true,"register_expires":120,"registrar_server":{"_parameters":{},"_headers":{},"_scheme":"sip","_user":null,"_host":"phone.plivo.com"},"connection_recovery_max_interval":20,"connection_recovery_min_interval":2,"via_host":"aeqf7b88emss.invalid","user_agent":"plivo-browser-sdk 2.1.20","plivosip_id":"out4c","hostport_params":"phone.plivo.com"},"_dynConfiguration":{"register":true},"_dialogs":{},"_applicants":{},"_sessions":{},"_transport":{"status":0,"socket":{"_url":"wss://phone.plivo.com:5063","_sip_uri":"sip:phone.plivo.com:5063;transport=ws","_via_transport":"WSS","_ws":{}},"sockets":[{"weight":0,"status":0}],"recovery_options":{"max_interval":20,"min_interval":2},"recover_attempts":0,"recovery_timer":null,"close_requested":false},"_contact":{"pub_gruu":null,"temp_gruu":null},"_status":1,"_error":null,"_transactions":{"nist":{},"nict":{},"ist":{},"ict":{}},"_data":{},"_closeTimer":null,"_registrator":{"_expires":120,"_call_id":"vsa32oc37nnu7143rk274o","_cseq":2,"_registrationTimer":131,"_registering":false,"_registered":true,"_contact":"<sip:r594n4dv#aeqf7b88emss.invalid;transport=ws>;+sip.ice;reg-id=1;+sip.instance=\"<urn:uuid:78fdf100-2c4d-4deb-a8ac-0cee371db730>\"","_extraHeaders":[],"_extraContactParams":""}},"_currentSession":null,"callSession":null,"callUUID":null,"callDirection":null,"lastCallUUID":null,"_lastCallSession":null,"incomingInvites":{},"incomingCallsInitiationTime":{},"lastIncomingCall":null,"callStats":{},"sipAuthBy":null,"userName":"david5719898358329549231","options":{"codecs":["OPUS","PCMU"],"enableTracking":true,"debug":"DEBUG","permOnClick":true,"enableIPV6":false,"audioConstraints":{},"dscp":true,"appId":"380077084","appSecret":null,"registrationDomainSocket":null,"clientRegion":null,"preDetectOwa":false,"disableRtpTimeOut":false,"allowMultipleIncomingCalls":false},"callstatskey":null,"rtp_enabled":null,"statsioused":false,"audio":{"ringtoneDevices":{},"microphoneDevices":{},"speakerDevices":{}},"owaLastDetect":{"time":0,"isOneWay":true},"owaDetectTime":3600000,"outBoundConnectionStages":[],"_outboundExtraHeaders":{},"_outboundCallNumber":null,"statsSocket":null,"bucketApiUrl":"https://stats.plivo.com/v1/browser/bucketurl/","bucketApiBody":{"username":"david5719898358329549231","password":"lokesh","domain":"phone.plivo.com"},"remoteView":{"width":0,"height":0},"ringToneView":{},"ringBackToneView":{},"connectToneView":{},"audioDevDic":["{\"deviceId\":\"default\",\"kind\":\"audioinput\",\"label\":\"Default\",\"groupId\":\"4ce38a6beefca1618312cc984683f32afdd8a031f04697ce4606940d6456d61b\"}","{\"deviceId\":\"d07a50eedfb049ab16b39ddbb545865947600d3673194a608af977f9ce1cf21f\",\"kind\":\"audioinput\",\"label\":\"Built-in Audio Analog Stereo\",\"groupId\":\"e8c51c00b437c50e95499ec3af71c3ad64bd7f204ee5dc3723471a9e0b8a5291\"}","{\"deviceId\":\"default\",\"kind\":\"audiooutput\",\"label\":\"Default\",\"groupId\":\"default\"}","{\"deviceId\":\"aef20cba2448b4d804e2e968682a01c4b1940595ca9b65de3acc0e16ea987338\",\"kind\":\"audiooutput\",\"label\":\"Built-in Audio Analog Stereo\",\"groupId\":\"e8c51c00b437c50e95499ec3af71c3ad64bd7f204ee5dc3723471a9e0b8a5291\"}"]}}"
endpointID: "001f922acfecfd9498ea0b2b84703ce8f14d2fa55dc96b857bfbfd1ffe9af40d"
AsteriskIntegration:Extension: ""
AsteriskIntegration:Context: ""
AsteriskIntegration:ToggleStatus: "Minimized"
AsteriskIntegration:ShowNotification: "0"
favorite_tables: "undefined"
debug: ""
csio_auth_data: ""eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWJtaXNzaW9uSW50ZXJ2YWwiOiI1MDAwIiwic2NvcGUiOlsicmVzdC1hcGktaDEiLCJyZXN0LWFwaSIsInN0b3JlLXNkcCIsImh0dHBzOi8vZXZlbnRzLWV1LXdlc3QtMS5jYWxsc3RhdHMuaW8vdjEvYXBwcyIsImh0dHBzOi8vc3RhdHMtZXUtd2VzdC0xLmNhbGxzdGF0cy5pby92MS9hcHBzIiwiaHR0cHM6Ly9hcHBzZXR0aW5ncy1ldS13ZXN0LTEuY2FsbHN0YXRzLmlvL3YxL2FwcHMiLCJodHRwczovL2Rhc2hib2FyZC1ldS13ZXN0LTEuY2FsbHN0YXRzLmlvL2FwcHMiXSwiY29sbGVjdFNEUCI6dHJ1ZSwiYWRhcHRpdmVJbnRlcnZhbCI6ZmFsc2UsImFkYXB0aXZlU3RhdHNFbmFibGVkIjpmYWxzZSwibXVsdGlTRFAiOmZhbHNlLCJ0YWFzRW5hYmxlZCI6ZmFsc2UsInJhd1VzZXJJRCI6ImRhdmlkNTcxOTg5ODM1ODMyOTU0OTIzMSIsInVzZXJJRCI6ImRhdmlkNTcxOTg5ODM1ODMyOTU0OTIzMSIsImp3dGlkQ2hhaW4iOlsiNDIiXSwiZW5kcG9pbnRUeXBlIjoiY2xpZW50IiwiYXBwSUQiOjM4MDA3NzA4NCwicmVzdEFwaVRyYW5zcG9ydCI6dHJ1ZSwicmVuZXdJbnRlcnZhbCI6MzQwMDAwMCwiZXhwaXJ5IjoiMjAyMC0wMy0xN1QwNToxNTo0NS45MDZaIiwib3JpZ2luIjpudWxsLCJpYXQiOjE1ODQ0MTg3NDUsImV4cCI6MTU4NDQyMjM0NSwianRpIjoiNWQ2ODg4YjctN2E3MC00ZTFkLWJmYTMtODA4MWJiOGYyNjRhIn0.41caOjpo4BbY7qknU9HV-R7HIKhb_4ZiybW6njYcnqQ""
AsteriskIntegration:UserID: "1"
AsteriskIntegration:SocketPort: ""
__proto__: Storage
_events: {}
_eventsCount: 0
_maxListeners: undefined
phone: e.exports {_events: {…}, _eventsCount: 7, _maxListeners: undefined, _cache: {…}, _configuration: {…}, …}
_currentSession: null
callSession: null
callUUID: null
callDirection: null
lastCallUUID: null
_lastCallSession: null
incomingInvites: Map(0) {}
incomingCallsInitiationTime: Map(0) {}
lastIncomingCall: null
callStats: a {}
sipAuthBy: null
userName: "david5719898358329549231"
options: {codecs: Array(2), enableTracking: true, debug: "DEBUG", permOnClick: true, enableIPV6: false, …}
callstatskey: "73aec46c-4893-41ff-aab9-aa23ef9df7f0"
rtp_enabled: true
statsioused: false
audio: {ringtoneDevices: {…}, microphoneDevices: {…}, speakerDevices: {…}, availableDevices: ƒ, revealAudioDevices: ƒ}
audioConstraints: {}
owaLastDetect: {time: 0, isOneWay: true}
owaDetectTime: 3600000
outBoundConnectionStages: []
_outboundExtraHeaders: {}
_outboundCallNumber: null
statsSocket: s {url: "wss://insights.plivo.com/ws", ws: WebSocket, userName: "david5719898358329549231", callstatskey: "73aec46c-4893-41ff-aab9-aa23ef9df7f0"}
statsCallback: ƒ ()
calcConnStage: ƒ (e)
str: ƒ (e)
bucketApiUrl: URL {href: "https://stats.plivo.com/v1/browser/bucketurl/", origin: "https://stats.plivo.com", protocol: "https:", username: "", password: "", …}
bucketApiBody: {username: "david", password: "abc", domain: "phone.plivo.com"}
remoteView: audio#plivo_webrtc_remoteview
ringToneView: audio#plivo_ringtone
ringBackToneView: audio#plivo_ringbacktone
connectToneView: audio#plivo_connect_tone
audioDevDic: (4) ["{"deviceId":"default","kind":"audioinput","label":…2c403010b9047aa8545d46eda66540c5d9fcd4cec87eb17"}", "{"deviceId":"d07a50eedfb049ab16b39ddbb545865947600…9ef43f5d3efef4e5adabc15779e3ce654fd2ff0ae4c72e7"}", "{"deviceId":"default","kind":"audiooutput","label":"Default","groupId":"default"}", "{"deviceId":"aef20cba2448b4d804e2e968682a01c4b1940…9ef43f5d3efef4e5adabc15779e3ce654fd2ff0ae4c72e7"}"]
plivoSocket: e.exports {_url: "wss://phone.plivo.com:5063", _sip_uri: "sip:phone.plivo.com:5063;transport=ws", _via_transport: "WSS", _ws: WebSocket, onconnect: ƒ, …}
heartbeatTimer: 85
__proto__: o
__proto__: Object
And below is my code to convert object to string.
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
var plivoBrowserSdkJSON = JSON.stringify(plivoBrowserSdk, getCircularReplacer());
I followed below answer.
How can I print a circular structure in a JSON-like format?
// create a class with constructor to reinitialise with the data only
You cant serialise function. Coz it is not enumeration properties
class SomeUtil {
constructor({ statsSocket, remoteView, ringToneView, ...rest }) {
this.statsSocket = statsSocket
this.remoteView = remoteView
this.ringToneView = ringToneView // some customization
Object.entries(rest).forEach(([key, value]) => {
this[key] = value
})
}
statsCallback() {
console.log(1)
}
}
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
// File one
function test1() {
const util = new SomeUtil();
util.remoteView = "audio#plivo_webrtc_remoteview"
const onSave = () => {
localStorage.setItem("SomeUtil", JSON.stringify(util, getCircularReplacer()))
}
}
// File 2
function test3() {
const util = new SomeUtil(localStorage.getItem("SomeUtil"));
console.log(util.remoteView)
}
//
I have only frontend code which works with API calls. I need to implement a similar page for photos with changing some parameters like job type, preference name, etc. When I changed job type=2, it always showed this error. I checked API with job type 2 on postman, It is working fine but not in the code and app.so what might be the error.for example,
SendNewJob: function (e) {
e.preventDefault();
$("#inputValidationErrorMessage").hide();
$("#extRefValidationErrorMessage").hide();
var existingToken = IO.LocalStorage.GetValue("userToken");
var frmData1 = new FormData();
var model = {
ThirdPartyClientId: Number($("#thirdPartyUser1").val()) || undefined,
JobType: 2,
Reference: $("#jobRefNr1").val(),
Notes: $("#notes").val(),
ExternalReference: $("#externalRefNr1").val() || undefined,
PreferenceNameId: Number($("#prefernceTypePhoto").val()) || undefined
};
and
service.js file
var ProjectConfigurationLevel =
{
Debug: 0,
Local: 1,
Live: 2
};
var FloorplanType =
{
Sketch: 1,
Draft: 2,
Ammendments: 3,
Final: 4
};
var MessageType =
{
Redirect: 0,
Info: 1,
Warning: 2,
Error: 3
};
var ForFront = {
Config: ProjectConfigurationLevel.Live,
Defaults: {
JobsPageSize: 5,
MaxPagesShown: 5
},
Urls: {
Live: "https://api.xyz.com/",
Debug: "http://test-api.xyz.com/",
Local: "http://192.168.60.75:3000/",
},
Links: {
SketchLocation: function () {
switch (ForFront.Config) {
case ProjectConfigurationLevel.Debug:
return "http://testsite.com/";
case ProjectConfigurationLevel.Local:
return "http://192.168.60.75:3001/";
case ProjectConfigurationLevel.Live:
return "http://testsite.com/";
default:
console.error("unknown config " + ForFront.Config);
break;
}
},
SubmitNewJob: function () {
var endpoint = "v1/Jobs";
When I execute my tests locally they pass with no problems but when tests proceed on the server I get:
TypeError: MouseEventConstructor is not a constructor (evaluating 'new MouseEvent('mousedown',
EXEC : error : TypeError: MouseEventConstructor is not a constructor (evaluating 'new MouseEvent('mousedown',
{
'which': 1,
'view': window,
'bubbles': true,
'cancelable': true
})')
for the code:
HTMLElement.prototype.mouseDownLeftButton = function () {
var event = new MouseEvent('mousedown',
{
'which': 1,
'view': window,
'bubbles': true,
'cancelable': true
});
this.dispatchEvent(event);
};
which is totally fine. Is there any other way to create a new MouseEvent ?
There is a polyfill from MDN that will resolve the issue:
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent#Polyfill
(function (window) {
try {
new MouseEvent('test');
return false; // No need to polyfill
} catch (e) {
// Need to polyfill - fall through
}
// Polyfills DOM4 MouseEvent
var MouseEvent = function (eventType, params) {
params = params || { bubbles: false, cancelable: false };
var mouseEvent = document.createEvent('MouseEvent');
mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
return mouseEvent;
};
MouseEvent.prototype = Event.prototype;
window.MouseEvent = MouseEvent;
})(window);
Most likely your local test infra uses real browser and on server it uses PhantomJS.
The latter still doesn't support new MouseEvent: https://github.com/ariya/phantomjs/issues/11289
I had to do the following trick to make tests pass:
function createMouseEvent(typeArg: string): MouseEvent {
let event = document.createEvent('MouseEvent');
event.initMouseEvent(typeArg,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined);
return event;
}
Im trying to wrap node js server in JS object,
In order to do that, I wrote this constructor:
function staticServerObj (rootFolder) {
this.rootFolder = rootFolder;
this.port = null;
this.isStarted = false;
this.startedData = null;
this.numOfCurrentRequests = 0;
this.numOfAllRequests = 0;
this.numOfSuccesfulRequest = 0;
this.serverObj = net.createServer(function (socket) {
handleNewConnection(this, socket);
});
};
The problem is, in handleNewConnection function, Im trying to use my staticServerObj vars (like: staticServerObj.port) and it's undefined,
Furthermore, when I try to log the server object in that way:
function handleNewConnection(server, socket) {
console.log(server);
}
Im getting this result:
{ domain: null,
_events: { connection: [Function] },
_maxListeners: 10,
_connections: 1,
connections: [Getter/Setter],
_handle:
{ fd: 12,
writeQueueSize: 0,
onconnection: [Function: onconnection],
owner: [Circular] },
_usingSlaves: false,
_slaves: [],
allowHalfOpen: false,
_connectionKey: '4:0.0.0.0:1234' }
Any Ideas?
You have a scoping problem. The this inside your createServer() does not point to the server object anymore. To solve this either save a reference to the staticServerObj like this:
function staticServerObj (rootFolder) {
this.rootFolder = rootFolder;
this.port = null;
this.isStarted = false;
this.startedData = null;
this.numOfCurrentRequests = 0;
this.numOfAllRequests = 0;
this.numOfSuccesfulRequest = 0;
var that = this;
this.serverObj = net.createServer(function (socket) {
handleNewConnection(that, socket);
});
};
or use bind() and have access to the this reference inside your function:
function staticServerObj (rootFolder) {
this.rootFolder = rootFolder;
this.port = null;
this.isStarted = false;
this.startedData = null;
this.numOfCurrentRequests = 0;
this.numOfAllRequests = 0;
this.numOfSuccesfulRequest = 0;
var that = this;
this.serverObj = net.createServer( handleNewConnection.bind( this ) );
};
function handleNewConnection(socket) {
// your former server variable can now be accessed using `this`
console.log( this );
}