How to get the response body with Node.js http.get?

Sometimes, we want to get the response body with Node.js http.get.

In this article, we’ll look at how to get the response body with Node.js http.get.

How to get the response body with Node.js http.get?

To get the response body with Node.js http.get, we can get it from the callback we pass into http.request.

For instance, we write

const options = {
  host: 'www.example.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

const req = http.request(options, (res) => {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log('body: ' + chunk);
  });
});

req.on('error', (e) => {
  console.log('problem with request: ' + e.message);
});

req.write('datan');
req.write('datan');
req.end();

to call http.request with the options object and a callback that has the res parameter.

In it, we call res.on with 'data' to listen to the data event which has the response data set as the value of chunk.

The data event is emitted when response data is received.

The response headers are in res.headers.

The response status code is in res.statusCode.

When there’s an error with the request, the 'error' event handler runs.

We listen for them with

req.on('error', (e) => {
  console.log('problem with request: ' + e.message);
});

And we call req.write to write data to the request body.

Finally, we close the handle with req.end.

Conclusion

To get the response body with Node.js http.get, we can get it from the callback we pass into http.request.