Categories
JavaScript Answers

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

Spread the love

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

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

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

To get data out of a Node.js HTTP get request with JavaScript, we can listen for the data event on the response.

For instance, we write

const callback = (response) => {
  let str = "";
  response.on("data", (chunk) => {
    str += chunk;
  });

  response.on("end", () => {
    console.log(str);
    // ...
  });
};

const req = http.request(options, callback).end();

to call http.request with the request options and a callback that calls response.one to listen for the 'data' event.

In the data event callback, we get the response chunk which has a chunk of the response body string.

We concatenate all the chunks into str so we get the full response body string.

When we get all the chunks, the end event is emitted and we log the value of str in the callback.

Conclusion

To get data out of a Node.js HTTP get request with JavaScript, we can listen for the data event on the response.

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 *