Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *