How to make HTTP requests in Node ?
In the world of REST API, making HTTP requests is the core functionality of modern technology. Many developers learn it when they land in a new environment. Various open-source libraries including NodeJS built-in HTTP and HTTPS modules can be used to make network requests from NodeJS.
There are many approaches to creating different kinds of network requests. Here, we will discuss 4 different approaches of them.
Table of Content
- Using AXIOS module
- Using SuperAgent Library
- 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 |
---|---|---|
GET | /posts | Listing all resources |
GET | /posts/<id> | Getting a resource |
POST | /posts | Creating 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:
The updated dependencies in package.json file will look like:
"dependencies": {
"axios": "^1.6.5",
"node-fetch": "^3.3.2",
"superagent": "^8.1.2",
}
Approach 1: Using AXIOS module:
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
Example: Below is code example to show the implementation of the HTTP request using axios module:
Javascript
const axios = require( "axios" ); // Make request axios .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
Output:
Approach 2 : Using SuperAgent Library:
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
Example: Below is code example to show the implementation of the HTTP request using SuperAgent Library:
Javascript
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:
Approach 3 : Using Node-Fetch module:
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
Example: Below is code example to show the implementation of the HTTP request using Node-Fetch module:
Javascript
const fetch = require( 'node-fetch' ); // Propmise then/catch block // Make request fetch( '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:
Approach 4 : Using HTTP module:
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.
Example: Below is code example to show the implementation of the HTTP request using HTTP modules:
Javascript
// 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:
Contact Us