I have been trying to get a query result from Arangodb in to my front end service(Angular 4) using soap message. I am able to get a result of the query but printed out in console.log. But how can I get it under this function(myService).
In other words, How can I feed my query result into a function rather than printing out the result in console. So that I can use this function to get the output of the query?
I have used .then() as well in order to get the promise.What am I still missing in it ?
server.js
var myService = db.query(aqlQuery`
LET startVertex = (FOR doc IN spec
FILTER doc.serial_no == '"123456abcde"'
LIMIT 2
RETURN doc
)[0]
FOR v IN 1 ANY startVertex belongs_to
RETURN v.ip`,
{
bindVar1: 'value',
bindVar2: 'value',
})..then(function(res) {
console.log("documents:" + res._result);
})
I would like to feed the function into soap msg and receive it Angular 4,
soap msg
var soap_msg = '<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:examples:CheckUserNameService">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
'<urn:CheckUserNameResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
'<status xsi:type="xsd:string">' + (myService) + '</status>' +
'</urn:CheckUserNameResponse>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
var server = http.createServer(function(request,response) {
response.end(soap_msg);
});
var port = 8000;
server.listen(port);
var soapServer = soap.listen(server, '/test', myService, xml);
But the output is either empty braces If I am using JSON.stringify or else it is [object Promise]. What am I doing wrong here ?
output
Related
I have function where I am using bpmn moddle to create bpmn xml.
Below is my function createFileData
import BpmnModdle from 'bpmn-moddle'
function createFileData(){
var moddle = new BpmnModdle()
var xmlStr =
'<?xml version="1.0" encoding="UTF-8"?>' +
'<bpmn2:definitions xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" ' +
'id="empty-definitions" ' +
'targetNamespace="http://bpmn.io/schema/bpmn">' +
'</bpmn2:definitions>';
moddle.fromXML(xmlStr, function(err, definitions) {
// update id attribute
definitions.set('id', 'NEW ID');
moddle.toXML(definitions, function(err, xmlStrUpdated){
console.log(xmlStrUpdated)
})
})
return xmlStrUpdated
}
I am getting the output in the console.
I want the xml created to be returned, when ever the function is called.
But I am getting the value as undefined and unable to return data to below function.
import createFileData from './fileData.js'
function viewxml(){
var data = createFileData()
console.log(data)
}
Can anyone help me in understanding, how to return the xml created from moddle?
I have a firebase function doing a http GET. There are 3 parameters and all works ok but if one of the parameters contains acentuation the Firebase console don't show any error but the the GET is not executed. In this case, the problem is with Parameter03.
var url = 'http://myapi.azurewebsites.net/api/values?Parameter01=' + nameParam + '&Parameter02=' + emailParam + '&Parameter03=' + serviceParam ;
http.get(url, (resp) => {
res.setEncoding('utf8');
}).on("error", (err) => {
console.log("Error : " + err.message);
});
Any help please ?
Whenever you build a URL, you should properly escape all the query string components so that they contain only valid characters. That's what encodeURIComponent() is for. So do encode all your query string values like this instead:
var url = 'http://myapi.azurewebsites.net/api/values' +
'?Parameter01=' + encodeURIComponent(nameParam) +
'&Parameter02=' + encodeURIComponent(emailParam) +
'&Parameter03=' + encodeURIComponent(serviceParam);
There are other cleaner ways to build a URL with query string components, but this should work fine.
I have two functions I am using to pull JSON from my server side to then display it to HTML.
The first function that pulls the data from the route handler is successfully pulling the data and parsing it successfully with JSON.parse() and displaying the needed information to the console without issue. I am not having and ajax or route handling issue...
Here is how I am dealing with the JSON first in my function called "projectInfo()":
projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// This console.log() prints the JSON string
// successfully pulled from route handler
// var projInfo is a local string var declared in the scope of
// this first function
console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo and store in string var p
// string var p is a local var declared inside of the scope
// of this function
p = JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p.Project);
// update "Global" pInfo with the value of the JSON data for
// "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
// This last console.log prints [object Object] to console
// How do I pul the value out of this Object?
The second function calls the first function in order to update a global variable with the parsed JSON data that I need to then display the global variable's data to the DOM element that I am trying to display.
Here is how I am trying to update my global var with a JSON Object in my function called "loginFun()":
// Call projectInfo() in order to update Global pInfo
// with the needed project info
projectInfo();
// This console.log() prints nothing...?
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// This is where I try to Display pInfo in the DOM but I only get Undefined...?
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
When I JSON.parse() the data in the first function I run a console.log() statement and I get the needed data to print from a variable local to the function I am getting my JSON with using ajax and I verify that the function is in fact doing what I need so that part is good up until I get the [object Object] output.
I am having issues when I call this function from my second function to then try to use the global variable which should have the data stored.
when I try to use the global variable with the needed data I get an 'undefined'...
I have also tried returning the data that has been parsed in the first function to then storehttps://codepen.io/lopezdp/pen/owKGdJ the value returned into a local variable in the second function but I still get 'undefined'.
If you would like to see the complete code for both functions I have put them on a CodePen to make it easier at:
https://codepen.io/lopezdp/pen/owKGdJ
How can I get my Project Data to display in my DOM element?
EDIT: The JSON Data that I am using looks like this:
{"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}
I rewrote your login function like this and it worked for me. I also eliminated the projectInfo() function!
var allMn = [];
var tags = [];
var pInfo = '';
function loginFun() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert("Required fields cannot be left blank.");
} else {
$.ajaxSetup({
cache: false
});
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/login/' + username + "zlz" + password,
cache: false,
success: function (data) {
// NEED SUB ROUTINE HERE FOR AJAX CALL DPL
// Make async call to ccdd tool database to get new data
// This collects allMn[] data!!!
getMnJson();
// END SUB ROUTINE HERE
// Checks to make sure user is logged in if not
// the condition redirects user to loginFun()
if (data.search("HTTP ERROR: ") != -1) {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
document.getElementById('searchResults').innerHTML = "Login Failed";
document.getElementById('searchRBar').style.display = "";
loginFun();
} else {
login = 1;
// Call projectInfo() in order to update pInfo with the needed project info
//projectInfo();
var projInfo = '';
var p = '';
// Get all Mn Data on startup tp display in DOM -DPL
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/role',
dataType: 'json',
cache: true,
success: function (data) {
// projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo
p = data['Project']; //JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p);
// update "Global" pInfo with the value of the JSON data for "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. /role data access Error.");
});
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// Display pInfo in the DOM
// document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
$("div.create").children().remove();
//-------------------------------------------------------------------END OF GLOBAL VARIABLES
$.ajaxSetup({
cache: false
});
// get table data from proxy server on port 7071 DPL
// NEED SUB ROUTINE HERE FOR AJAX CALL
// Make call to server-side code to reload JSON data into table from port 7071
pushJsonData();
// END SUB ROUTINE HERE!!!
// getTblJson();
}
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. Need user Credentials");
});
}
}
I am fairly new to js and node.js but I have managed to get the calls going to the API and getting the necessary information. However when I was attempting to continue to raise the batter id to get the next information available. I have successfully gotten the undefined error check to work as well. But I was unable to loop through because I was trying to perform something immediately on an async function. I am now trying to make the entire function async with a 2 second delay after each run, but it is returning the following error (i'm assuming because something is undefined)
**Note: When I just get the value for i=4 and p=1 the value does exist in the API data. However it gives this error when I attempt to start with those values using this code.
error:
Unexpected token u in JSON at position 0
this is my code:
request('API Info redacted',
setTimeout (function (err, response, body) {
//do stuff below
//to get the first play of the game, set i=1 and p=0
var i = 4;
var p = 1;
// ************
var boolIn = 1;
// parse the body as JSON
var parsedBody = JSON.parse(body);
var apiResults = parsedBody.apiResults;
if( typeof(apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p]) == 'undefined') {
//sets the variables to the first batter of the next inning
p=0;
i = i+1;
}
//below pulls the apiResults from the body of the API request
var sportId = apiResults.sportId;
var hitName = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].name;
var fname = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].batter.firstName;
var lname = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].batter.lastName;
var outsB = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].outs.before;
var outsA = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].outs.after;
var rbis = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].runsBattedIn;
var outDifference = (outsA - outsB);
var hitB = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].baseSituation.beforeId;
var hitA = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].baseSituation.afterId;
var baseDifference = (hitA - hitB);
//prints the details pulled above
res.json("First Name: " + fname + ", Last Name: " + lname + ", Hit name: " + hitName + ", Outs on the play: " + outDifference + ", Rbi's: " + rbis +
", Base Sit: " + baseDifference);
//increases the batter call
p = p+1;
//below ends the setTimeout
}, 2000));
//ended request
});
setTimeout will not pass arguments to the function it calls, so body is undefined. When you pass that to JSON.parse, it will be converted to the string "undefined", which isn't a valid JSON text.
Nowhere is your code do you show any JSON coming into your program (or embedded into it). You need to have some JSON to parse before you try to parse it.
I was doing some basic JSON parsing and wondered why node js collapses the objects when it is logged together with string
so for example in the code below, if I go console.log(processedData) it won't collapse the object and show the whole string but if I go console.log('Body: ' + processedData) it collapses the objects and goes [object Object][object Object].... I know how to expand them again using util but I was curious on the logic behind it as I am quite new to node. I think I might be missing out on something.
const http = require('http');
const util = require('util');
var options = {
host: 'http://nodejs.org/dist/index.json'
// host: 'en.wikipedia.org',
// path: '/w/api.php?action=query&list=allpages&apfrom=Imperial&aplimit=500&format=json'
};
var req = http.get('http://nodejs.org/dist/index.json', function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
let body = '';
res.on('data', function(chunk) {
body += chunk;
}).on('end', function() {
let processedData = JSON.parse(body);
console.log('Body : ' + processedData);
console.log(typeof body);
})
});
req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
When you call
console.log(processedData)
You're passing the entire object to console.log for it to do it's thing. However, when you call
console.log('Body: ' + processedData)
You're passing the result of 'Body: ' + processedData to console.log. The evaluation of this expression causes processedData to be converted to its string representation, which if you haven't defined toString on your object, will just be [object Object], so you see Body: [object Object] being logged.
The simplest way to achieve what you're after is to simply pass them as separate arguments:
console.log('Body: ', processedData)
Maybe we should answer following questions: "If you do the operation like below - what is expected a type of result?"
var myVar = "Body : " + processData;
When js engine tries to evaluate such expression it knows that first parameter of the expression is 'string', so it tries to concatenate the string with another string. How processData become a string? By calling 'toString()' on processData.
To achieve the result you expect, to try to use console.log in that way:
console.log("Body:", processData);
This is because JS type coercion.
In first case you print it as object, but in second, you add it to the string ('Body: ' + processedData) - and according to JS type coercion rules it converts it to string (it concatenates it to string)
You can use util module as you suggested, or to use console.dir({body:processedData},{colors:true,depth:4});