I have manage to get an API working for a product I have started to use, I can successfully run the below code and update a record in the api's database (I have removed all the api's soap xml code to make it look cleaner), I am trying to save the output as a variable so i can then process it in php,
I am a beginner to Javascript but I cant find much help on saving the output.
If someone could point me in the right direction I would be forever grateful,
I just need to console.log output in a variable rather than in the console.
var https = require("https");
var xml =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">' +
'<soap:Header>' +
'</soap:Header>' +
'<soap:Body>' +
'</soap:Body>' +
'</soap:Envelope>';
var username = "";
var password = "";
var options = {
host: "",
port: 443,
method: "POST",
path: "",
// authentication headers
headers: {
'Content-Type': "text/xml; charset=utf-8",
'Content-Length': Buffer.byteLength(xml),
'Authorization': "Basic " + new Buffer(username + ":" + password).toString("base64"),
'SOAPAction': "",
'Accept': "application/json"
}
};
//The call
request = https.request(options, function (res) {
console.log("statusCode:", res.statusCode);
res.on("data", (d) => {
process.stdout.write(d);
});
});
request.on("error", (e) => {
console.error(e);
});
request.end(xml);
If you want to save the output, then you need to save the data from the variable that contains the output (which you have called d).
console.log("statusCode:", res.statusCode);
var data = "";
res.on("data", (d) => {
data += d;
});
res.on("end", x => {
// data is now ready
});
Note that you will probably run into the issue described in this question and you would probably be better off using an HTTP client library that natively supported promises, such as Axios.
Related
I am trying to get data via external API but it comes in XML. I would like to convert it to JSON before using it on another function. Anyone with an idea on how to do this, kindly help. Here is my code.
function getData() {
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + ak
}
};
var url = 'https://data.purelyhr.com/daily?ak='+ ak + '&sDate=' + start + '&eDate=' + end + '&TimeOffTypeName';
var response = UrlFetchApp.fetch(url, options);
var response = xmlToJSON.parseString(response);
Logger.log(response)
}
I'm adding a contact me section to a website. I want to be able to send the data from the forms with JS, and then receive and do something with the data with Node. I understand that there are frameworks and libraries that can handle this stuff, but I would like to build it from scratch so that I have a better understanding of what is happening.
I currently have a section of JS (see below) that is taking the form data, and sending it as a POST request to the node script, but I can't seem to wrap my head around what is happening with node, or how to receive the data with the node script. Any help in pointing me in the right direction is greatly appreciated.
const name = $(".name");
const email = $(".email");
const message = $(".message");
const submitButton = $(".submitButton");
const nameRegex = /([a-zA-Z\s-])/g;
const emailRegex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/g;
const messageRegex = /([a-zA-Z\s.,?!$%&])/gm;
const url = "../node/contactMeSubmissionHandler.js"
submitButton.click(function(){
let nameContents = name.val().match(nameRegex).join("");
let emailContents = email.val().match(emailRegex).join("");
let messageContents = message.val().match(messageRegex).join("");
// if (emailRegex.test(emailContents) == true) {
// let emailValid = emailContents;
// } else {
// console.log("Email is invalid");
// };
const data = {
email: emailContents,
name: nameContents,
message: messageContents
}
$.post(url, data, function(data, status){
console.log(`${data} and status is ${status}`);
})
})
I like to write from scratch too. Here is working code which is called from a command line to get a token.
// clientEx.js
var http = require('http');
var fs = require('fs');
const _SERVER = "dcsmail.net"; /* dcsmail.net */
// Callback function is used to deal with response
//
var callback = function (response)
{
// update stream with data
var body = '';
response.on('data', function(data) {
body += data;
});
response.on ('end', function()
{
// Data received completely.
fs.writeFileSync ("temp.lst", body, 'utf8');
// console.log ("clientEx.js received: " + body);
});
}
if ((process.argv[2] == null) || (process.argv[3] == null) || (process.argv[4] == null) || (process.argv[5] == null))
{
console.log ("clientEx.js usage:<user email> <user password> <destination> <GUID>");
}
else
{
var Ef_email = encodeURI (process.argv[2]);
var Ef_pass = encodeURI (process.argv[3]);
var Ef_dest = encodeURI (process.argv[4]);
var Ef_guid = encodeURI (process.argv[5]);
var post_data = ("f_email=" + Ef_email +
"\&" + "f_pass=" + Ef_pass +
"\&" + "f_dest=" + Ef_dest +
"\&" + "f_guid=" + Ef_guid);
// Options to be used by request
var options = {
host: _SERVER,
port: '80',
path: '/DCSM/tokenP10.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength (post_data)
}
};
// console.log ("clientEx.js using " + _SERVER + ":" + options.port + options.path);
// request the token from the host
try
{
var req = http.request (options, callback);
req.write (post_data);
req.end();
}
catch (error)
{
fs.writeFileSync ("temp.lst", "Host access failed\n", 'utf8');
}
}
You should be able to adapt that to your needs.
Use this code to create a server and check the log in console for different request attributes.
const http = require('http');
http
.createServer((request, response) => {
console.log(request);
response.end();
})
.listen(3000);
Make GET and POST request to http://localhost:3000/ and look for method, headers etc.
See more here and here.
All,
I am trying to figure out how to pass the results from an https.request in node.js code out to a variable. I have an https.request setup that correctly passes the correct information to a SOAP API and gets the correct response back. My ultimate goal is to get the output from the https.request into a variable that I can call using Express.
Here is are my code chunks.
HTML:
<div class="row">
<div class="col-md-12" class="pull-left">
<p> TEST </p>
<p>{{soapreply}}</p>
</div>
JS:
app.post('/cucmmapper/submit', function (req, res) {
// FORM - DATA COLLECTION
var cucmpub = req.body.cucmpub;
var cucmversion = req.body.cucmversion;
var username = req.body.username;
var password = req.body.password;
var authentication = username + ":" + password;
var soapreplyx = '';
// SOAP - BUILD CALL
var https = require("https");
var headers = {
'SoapAction': 'CUCM:DB ver=' + cucmversion + ' listCss',
'Authorization': 'Basic ' + new Buffer(authentication).toString('base64'),
'Content-Type': 'text/xml; charset=utf-8'
};
// SOAP - AXL CALL
var soapBody = new Buffer('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.cisco.com/AXL/API/11.5">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
'<ns:listCss sequence="?">' +
'<searchCriteria>' +
'<name>%</name>' +
'</searchCriteria>' +
'<returnedTags uuid="?">' +
'<name>?</name>' +
'<description>?</description>' +
'<clause>?</clause>' +
'</returnedTags>' +
'</ns:listCss>' +
'</soapenv:Body>' +
'</soapenv:Envelope>');
// SOAP - OPTIONS
var options = {
host: cucmpub, // IP ADDRESS OF CUCM PUBLISHER
port: 8443, // DEFAULT CISCO SSL PORT
path: '/axl/', // AXL URL
method: 'POST', // AXL REQUIREMENT OF POST
headers: headers, // HEADER VAR
rejectUnauthorized: false // REQUIRED TO ACCEPT SELF-SIGNED CERTS
};
// SOAP - Doesn't seem to need this line, but it might be useful anyway for pooling?
options.agent = new https.Agent(options);
// SOAP - OPEN SESSION
var req = https.request(options, function (res) {
res.setEncoding('utf8');
res.on('data', function (d) {
soapreplyx = d;
console.log("Got Data: " + d);
});
});
// SOAP - SEND AXL CALL
req.write(soapBody);
res.render('cucmmapper-results.html'), {
'title': 'CUCM 2.1',
'soapreply': soapreplyx
};
req.end();
req.on('error', function (e) {
console.error(e);
});
});
}
The line "console.log("Got Data: " + d)" is getting the correct expected reply from the API, however, I can't figure out how to get that data into my variable "soapreplyx" which changes in Express to "soapreply".
Much appreciated for any help you might have!
You're not waiting for your request to respond before you call res.render(), so the value of soapreplyx is always '', its initial value. To correct this, add an 'end' event listener on the response object passed to your https.request() callback.
You're not appending the chunks of the response to your soapreplyx variable, you're reassigning its value with each successive chunk.
let soapRequest = https.request(options, soapResponse => {
soapResponse.on('data', chunk => {
soapreplyx += chunk
})
soapResponse.on('end', () => {
return res.render('cucmmapper-results.html', {
title: 'CUCM 2.1',
soapreply: soapreplyx
})
})
})
soapRequest.write(soapBody)
soapRequest.end()
Parse.Cloud.job("syncMetadataWithContentPortal", function(request, status) {
var apikey ="49eiivmz";
var uid = "t1g4Y2jC6S";
Parse.Cloud.httpRequest({
url: 'https://api.parse.com/1/functions/getContentMetaData',
method: 'GET',
headers : {
'Content-Type': 'application/json',
'X-Parse-Application-Id':'appkey',
'X-Parse-REST-API-Key':'restapikey',
},
body: {
apiKey : apikey
}
}).then(function(httpResponse) {
Parse.Cloud.useMasterKey();
status.message(httpResponse.text);
console.log(httpResponse.text);
var contents = JSON.parse(httpResponse.text);
var contentIdCollection = [];
for (var i = 0; i < contents.length; i++) {
contentIdCollection.push(contents[i].id);
}
status.success('Content Synced');
}, function(httpResponse) {
// console.error('Request failed with response code ' + httpResponse.status);
status.error('Request failed with response code ' + httpResponse.status)
});
});
So I have a job making httpRequest to call a function getContentMetaData which requires API key as a parameter.
How do I send parameters using GET method?
I got status as :Request failed with response code 405
Please help me how to solve this. Thanks in advance.
Don't use Parse.Cloud.httpRequest to call other cloud functions, instead you should be using Parse.Cloud.run
Your problem could also be related to your headers as you appear to be using string literals instead of variable references.
I have tried a bit of code to upload a file on node based server and i'm getting a socket hang up error.
After googling about the error I came across a post which suggested that request.end() if not called causes this error but as you will see code below I do have called request.end().
Any help,suggestion are appreciated
var http = require('http');
var fs = require('fs');
var options = {
hostname: 'api.built.io',
port : 443,
path : '/vi/uploads',
method : 'POST'
};
var request = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
var size;
fs.stat('/home/abhijeet/Downloads/fgo-2.jpg',function(err,stats){
size = stats.size;
console.log(size);
});
var boundaryKey = Math.random().toString(16); // random string
request.setHeader('Content-Type', 'multipart/form-data; boundary="'+boundaryKey+'"');
request.setHeader('application_api_key','1234');
request.setHeader('authtoken','123');
request.setHeader('Content-Length','42215');
// the header for the one and only part (need to use CRLF here)
request.write(
'--' + boundaryKey + '\r\n'
// use your file's mime type here, if known
+ 'Content-Type: image/jpeg\r\n'
// "name" is the name of the form field
// "filename" is the name of the original file
+ 'Content-Disposition: form-data; name="upload[upload]"; filename="/home/abhijeet/Downloads/fgo-2.jpg"\r\n'
+ 'Content-Transfer-Encoding: binary\r\n\r\n'
);
var readFile = fs.createReadStream('/home/abhijeet/Downloads/fgo-2.jpg', { bufferSize: 4 * 1024 })
.on('end', function() {
request.end('\r\n--' + boundaryKey + '--'); // mark the end of the one and only part
})
.pipe(request, { end: false }) // set "end" to false in the options so .end() isn't called on the request
request.on('error',function(error){
console.log(error);
});
// maybe write directly to the socket here?
request.end();
// console.log(readFile);