Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
Express.JS Get Status Code from POST Request

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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();
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!