I am needing to find a way to get a response as a result of a https post request. So far from what I hae found that is only provided in the call back function, which does not include the result after data is written to the request and is ended as shown below:
**Note: the code below would be wrapped inside a "app.post" method.
const https = require("https");
var url = "https://someurl.com";
var options = {option1: "some option"}
var jsonData = {data1: "some data"};
const request = https.request(url, options, function (repsonse) {
// HERE THE STATUS CODE ONLY CAPTURES IF THE RESOURCE WAS AVAILABLE
// NOT IF THE REQUEST WAS SUCCESSFUL
console.log(response.statusCode);
});
request.write(jsonData);
request.end();
After the "request.end()" code i need to be able to get the status code returned from the request to determine if the actual request was successful. I would want to do something like this:
if (response.statusCode !== 200) {
res.sendFile(__dirname "/failure.html");
}
else {
res.sendFile(__dirname "/success.html");
}
The if statement should run after request.end() to determine if the actual request was successful. This is standard for using API frameworks such as Flask-Python, but I can't seem to find a way to catch this in express.js. Any help would be appreciated.
CodePudding user response:
https.request
works asynchronously. Whether the request is successful or not cannot be determined synchronously after the request.end()
, but only in the callback function (where you can evaluate response.statusCode
) or in the error
event (if the request could not be made at all, for example because the server was unreachable).
const request = https.request(url, options, function (response) {
console.log(response.statusCode);
if (response.statusCode !== 200)
res.sendFile(__dirname "/failure.html");
else
res.sendFile(__dirname "/success.html");
});
request.on("error", function(err) {
console.error(err);
res.sendFile(__dirname "/failure.html");
});
request.write(jsonData);
request.end();