How to make HTTP requests in Node.js ? - GeeksforGeeks

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. 
Using AXIOS moduleUsing SuperAgentUsing Node-Fetch moduleUsing HTTP module
Using AXIOS module
Using SuperAgent
Using Node-Fetch module
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
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 requestaxios.get('https://jsonplaceholder.typicode.com/posts/1')    // 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
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(  'https://jsonplaceholder.typicode.com/posts')                             .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 requestfetch('https://jsonplaceholder.typicode.com/posts/1', {  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 moduleconst http = require('http');  // Setting the configuration for// the requestconst options = {    hostname: 'jsonplaceholder.typicode.com',    path: '/posts',    method: 'GET'};    // Sending the requestconst 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
http request response
Conclusion: My personal choice is Axios, but there are some other popular libraries on npm, take a look:
Request
GOT
Needle
Node.js-HTTP-Module
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript