Get reponse message in Node using Request library?

1.9k Views Asked by At

My backend server has the following code using Express:

router.post('/test', function(req, res) {
  res.end(res.writeHead(200, "custom message");
});

When I make this post request in Node.js using Request library how do I get the "custom message"?

var request = require("request");
request.post(options, function(error, response, body) {
  console.log(response.statusCode); //works
  console.log(JSON.stringify(response.headers)); //doesn't have my custom message 
});

In c# I was able to get this message in the statusDecription property, how does it work in Request library?

Edit: Solved with the following code:

router.post('/test', function(req, res) {
  res.end(res.writeHead(200, {"test": "custom message"});
});

then

var request = require("request");
request.post(options, function(error, response, body) {
  console.log(response.headers["test"]);  
});
1

There are 1 best solutions below

1
On

From the http.ServerResponse API:

response.writeHead(statusCode[, statusMessage][, headers])

Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument.

The response argument in the request callback is an instance of http.ServerResponse. What you're looking for is in the response.statusMessage.

https://nodejs.org/api/http.html#http_class_http_serverresponse