How to make HTTP Requests in native Node.js

In an earlier article, we learned about different ways to make HTTP requests in Node.js using various popular libraries such as Axios, Needle, and more.

These libraries are simple and hide the underlying complexity of dealing with HTTP requests in native Node.js. But it also requires external dependencies.

In this short article, you will learn about Node.js native HTTPS module to make HTTP requests without any external dependency.

Since it is a native module, no installation is required. You can access it in your code like below:

const https = require('https');

GET Request

Here is a simple example that uses the HTTPS module's https.get() method to send a GET request:

const https = require('https')

https
  .get('https://reqres.in/api/users', res => {
    let data = ''

    // called when a data chunk is received.
    res.on('data', chunk => {
      data += chunk
    })

    // called when the complete response is received.
    res.on('end', () => {
      console.log(JSON.parse(data))
    })
  })
  .on('error', err => {
    console.log('Error: ', err.message)
  })

Unlike other popular HTTP clients that collect the response and return it as a string or a JSON object, here, you need to concatenate the incoming data stream to use it later.

Another notable exception is the HTTPS module does not support promises, which makes sense as it is a low-level module and is not very user-friendly.

POST Request

To make a POST request, we have to use the generic https.request() method. There is no shorthand https.post() method available.

The https.request() method accepts two parameters:

  1. options — It can be an object literal, a string or a URL object.
  2. callback — The callback function captures and processes the response.

Let us make a POST request:

const https = require('https')

const data = JSON.stringify({
  name: 'John Doe',
  job: 'DevOps Specialist'
})

const options = {
  protocol: 'https:',
  hostname: 'reqres.in',
  port: 443,
  path: '/api/users',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
}

const req = https
  .request(options, res => {
    let data = ''

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

    res.on('end', () => {
      console.log(JSON.parse(data))
    })
  })
  .on('error', err => {
    console.log('Error: ', err.message)
  })

req.write(data)
req.end()

The protocol and port attributes in the options object are optional.

PUT and DELETE Requests

The PUT and DELETE request formats are similar to a POST request. Only change the options.method value to PUT or DELETE.

Here is an example of a DELETE request:

const https = require('https')

const options = {
  hostname: 'reqres.in',
  path: '/api/users/2',
  method: 'DELETE'
}

const req = https
  .request(options, res => {
    // log the status
    console.log('Status Code:', res.statusCode)
  })
  .on('error', err => {
    console.log('Error: ', err.message)
  })

req.end()

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.