How to get data out of a Node.js HTTP get request?

Sometimes, we want to get data out of a Node.js HTTP get request.

In this article, we’ll look at how to get data out of a Node.js HTTP get request.

How to get data out of a Node.js HTTP get request?

To get data out of a Node.js HTTP get request, we can get the data from the data event callback.

For instance, we write

const http = require('http')

http.get(options, (response) => {
  response.setEncoding('utf8')
  response.on('data', console.log)
  response.on('error', console.error)
})

to call http.get to make a HTTP GET request.

We get the request response from the 'data' event payload.

To get the data from the payload, we call response.on with 'data' and a callback that has the response data in the first parameter.

Therefore, when the 'data' event callback is run, we see the response data logged with console.log.

Conclusion

To get data out of a Node.js HTTP get request, we can get the data from the data event callback.