Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to make HTTP requests in Node.js ?

  • Last Updated : 29 Sep, 2021

In the world of REST API, making a HTTP request is the core functionality of modern technology. Many developer learn it when they land to a new environment.  Various open-source library including NodeJS built in HTTP and HTTPS modules can be used to make network request from NodeJS.

There are many approaches to create different kinds of network requests. Here,  we will discuss 4 different approaches of them. 

  1. Using AXIOS module
  2. Using SuperAgent
  3. Using Node-Fetch module
  4. Using HTTP module

Here, we will send the request to https://jsonplaceholder.typicode.com/ API and show the response’s data. Here are our all REST APIs.

 

Method

REST API

Detail

GET/postsListing all resources
GET/posts/<id>Getting a resource
POST/postsCreating a resource
PUT/posts/<id>Updating a resource

Setup a new project: To create a new project, enter the following command in your terminal.

mkdir test
npm init -y

Project Structure: It will look like the following.  

project-directory

Approach 1:  In this approach we will send request to getting a resource using AXIOS library. Axios is a promise base HTTP client for NodeJS. You, can also use it in the browser. Using promise is a great advantage when dealing with asynchronous code like network request. 

Installing module:

npm i axios

Create index.js and write down the following code.



index.js




const axios = require('axios')
  
// Make request
  
  // Show response data
  .then(res => console.log(res.data))
  .catch(err => console.log(err))

Step to run the application: Open the terminal and write the following command.

node index.js

Output:

axios request response

Approach 2 : Here we will make a request to creating a resource using SuperAgent library. This is another popular library  for making network requests in the browser but works in Node.js as well. 

Installing module:

npm i superagent

Rewrite the index.js with the following code.

index.js




const superagent = require('superagent');
  
// promise with async/await
(async () => {
  
    // Data to be sent
    const data = {
        title: 'foo',
        body: 'bar',
        userId: 1,
    }
  
    try {
  
        // Make request
        const {body} = await superagent.post(
                             .send(data)       
        // Show response data
        console.log(body)
    } catch (err) {
        console.error(err)
    }
  })();

Step to run the application: Open the terminal and write the following command.

node index.js

Output:

superagent request response

 

Approach 3 : Here we will send a request to updating a resource using node-fetch library. If you are already worked with Fetch in browser then it may be your good choice for your NodeJS server. 

 



Installing module:

npm i node-fetch

Rewrite the index.js with the following code.

index.js




const fetch = require('node-fetch');
  
// Propmise then/catch block
// Make request
  method: 'PUT',
  body: JSON.stringify({
    id: 1,
    title: 'fun',
    body: 'bar',
    userId: 1,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  // Parse JSON data
  .then((response) => response.json())
  
  // Showing response
  .then((json) => console.log(json))
  .catch(err => console.log(err))

Step to run the application: Open the terminal and write the following command.

node index.js

Output:

node-fetch request response

Approach 4 :  Here we will send a request to getting all resource using HTTP module. NodeJS have built in HTTP module to make network request. But the drawbacks is that, it is not too user friendly like the other solution. You, need to manually parse the data after received.

Installing module: It is a built-in module, doesn’t need to install. Just plug and play. 

Rewrite the index.js with the following code.

index.js




// Importing https module
const http = require('http');
  
// Setting the configuration for
// the request
const options = {
    hostname: 'jsonplaceholder.typicode.com',
    path: '/posts',
    method: 'GET'
};
    
// Sending the request
const req = http.request(options, (res) => {
    let data = ''
     
    res.on('data', (chunk) => {
        data += chunk;
    });
    
    // Ending the response 
    res.on('end', () => {
        console.log('Body:', JSON.parse(data))
    });
       
}).on("error", (err) => {
    console.log("Error: ", err)
}).end()

Step to run the application: Open the terminal and write the following command.

node index.js

Output: 

http request response

Conclusion: My personal choice is Axios, but there are some other popular libraries on npm, take a look:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!