Making HTTP Requests in Node.js Using Core Modules

In Node.js, it's possible to make HTTP requests without relying on external libraries like Axios or node-fetch, simply by using the core http and https modules. This approach is useful for keeping dependencies low and having more direct control over request handling.

Using the http Module

To make an HTTP request, we can use the built-in http module in Node.js. Here's an example of a GET request:


const http = require('http');

const options = {
  hostname: 'example.com',
  port: 80,
  path: '/',
  method: 'GET'
};

const req = http.request(options, res => {
  console.log(`Status Code: ${res.statusCode}`);

  res.on('data', chunk => {
    console.log(`Body: ${chunk}`);
  });

  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', error => {
  console.error(`Error: ${error.message}`);
});

req.end();

Using the https Module

If you need to make a request to a server using HTTPS, you should use the https module. The code is very similar:


const https = require('https');

const options = {
  hostname: 'example.com',
  port: 443,
  path: '/',
  method: 'GET'
};

const req = https.request(options, res => {
  console.log(`Status Code: ${res.statusCode}`);

  res.on('data', chunk => {
    console.log(`Body: ${chunk}`);
  });

  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', error => {
  console.error(`Error: ${error.message}`);
});

req.end();

Important Notes

  • Remember to call req.end() to actually send the request, even if you're not sending any data in the body.
  • You can also add custom headers inside the options object.
  • For POST or PUT requests, you can write data using req.write(data) before calling req.end().

Conclusion

The http and https modules in Node.js provide a fairly simple and direct API for making web requests. While it may seem more verbose at first compared to modern libraries, understanding these basics is fundamental to better grasp how network communication works in the Node.js environment.

Back to top