PASSWORD RESET

Your destination for complete Tech news

How to make an HTTP request in Node JS?

347 0
< 1 min read

In Node.js, you can make an HTTP request using the built-in http or https modules. Here’s an example of making an HTTP GET request using the http module:

const http = require('http');

http.get('http://example.com', (response) => {
  let data = '';

  response.on('data', (chunk) => {
    data += chunk;
  });

  response.on('end', () => {
    console.log(data);
  });
}).on('error', (error) => {
  console.error(error);
});

This code makes an HTTP GET request to http://example.com. When the response is received, the response data is concatenated to a string variable data and the final response is printed to the console.

The http.get() method takes two arguments: the URL to make the request to, and a callback function that is called when the response is received. The callback function takes a response object as an argument, which represents the response from the server.

Inside the callback function, we listen for the data and end events on the response object to read the response data. The data event is emitted whenever a new chunk of data is received, and the end event is emitted when the response is complete.

Finally, we listen for the error event on the http.get() method to handle any errors that may occur during the request.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.