0

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);
Danishan
  • 65
  • 1
  • 10
  • Why PHP? Aren't you using node? And what exactly do you mean by "save"? Do you want to store the result in a file? Or use it for your next API call? Please elaborate. –  Mar 04 '19 at 20:51
  • Take a look at [request](https://github.com/request/request#readme) it can help you handle the API response in a simpler way – Thom Mar 04 '19 at 20:52
  • @ChrisG It's the example code the api has given me. I was hoping once I get the data out of this SOAP call I can just manipulate it in a language that I understand. – Danishan Mar 04 '19 at 21:23
  • I'm sorry, but you haven't answered any of my questions. Taken at face value, the answer is "do something else with `d`" in the callback. But without having any idea of what you're trying to achieve, I can't really be more helpful. –  Mar 04 '19 at 21:27

1 Answers1

1

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335