Making HTTP requests is one of the everyday tasks done by using Node.js. You will get a massive set of libraries consisting of modules for various purposes. One of the commonly used modules of Node.js is the HTTP/HTTPS module. Most developers look for this module while migrating to the new environment, as HTTP/HTTPS requests are the core functionality for any application to function correctly. With the best node.js course, you can understand all the basics clearly.
If you do not want to use the HTTP/HTTPS module, you can use any of the available npm packages to solve your purpose of creating an HTTP request. In this article, we will highlight the simple steps to make an HTTP request with the help of the HTTP module on the Node web server. This module is an in-built module with Node.js installation and npm packages, such as Axios, Got SuperAgent, and node-fetch.
Prerequisites
You cannot just start working with Node.js with a proper working environment setup. You need to fulfill some prerequisites before you dive into the coding part. So, let’s see what conditions you need to maintain to start coding with Node.js.
- First, before you start coding, check if you have the latest version of Node.js installed on your system. If you do not have one, then install the newest version. Also, in this article, we will be using examples running in Node.js version 14.x, the active LTS.
- Also, you must know how to run npm commands in node.js, such as npm init. Ensure that you install the required packages beforehand to avoid the inconvenience while running the actual code.
- You must know how to run JavaScript files with proper commands.
- You must have a basic understanding of Node.js, as you need to deal with technical stuff here. You must go for the best full-stack web development bootcamp for more specialized knowledge.
Getting HTTP(S) Request
The HTTP module is the default module in the standard library of Node.js. You can use this module and start coding without installing and managing the external dependencies. But, while using it, you will face some challenges as it is not a user-friendly module compared to others.
We have used some examples from GitHub, the open-source repository of all codes, for your better understanding. Here, we are making a GET request using the HTTP client option by calling the stored data from JSONPlaceholder mock API. as a response to the completed request, it will send the data of the ten users along with their names and ID. in this article, we have mentioned different type of examples showing callback-based, promise-based, and async/await.
Five different methods are discussed for making the GET HTTP call to the placeholder API. Node.js offers an HTTP built-in module to perform several HTTP-related tasks to make your job easier.
Before further discussion, you must consider the following points about the HTTP/HTTPS module.
- First thing, the HTTP and HTTPS modules provide low-level functionality. Once you make the request, you will get the required response in chunks rather than getting all the results. Not only this, you have to parse the received response manually. It might get straightforward for the JSON format, but still, you need to put extra effort into parsing the complete answer.
- Second, your HTTP module will not support the HTTPS requests by default. So, you need to use the HTTPS module if the HTTPS requests are made while communicating.
Despite the above challenges, the HTTP/HTTPS module is helpful as you will be saved by eliminating the reliability of several dependencies.
Request Module
Request module is a more user-friendly option than the HTTP module to make HTTPS calls. Even the community people are considering it. But, unlike the HTTP module, you need to install the request module as an npm package.
Hit the following command from the terminal to install the request module using npm.
npm install request
But, this module has been deprecated after 2020 as there have been no changes made to this module. After installing the request module, run the following command to verify the version.
npm version request
This module supports the HTTPS calls and redirects by default. In the below example, the code resides in the request body of the code.
For example-
const request = require('request');
//python requests body
request('https://jsonplaceholder.typicode.com/users', { json: true }, (err, res, body) => { if (err) {
return console.log(err); }
console.log(body.url);
console.log(body.explanation);
});
post request body with Curl
If you want to post the data within the request message body using Curl, you must pass the required data to Curl. Using the -d or –data command line switch, you can do this. With the help of the Content-Type header, you can specify the data type of the message you want to include. The Node HTTP server uses this header to interpret and process the data in the POST message body.
For example, for sending the JSON to the Node.js web server, you need to specify the data type in the body with the help of the Content-Type: application/json header.
For example-
//curl post body
curl -X POST https://reqbin.com/echo/post/json
-H "Content-Type: application/json"
-d '{"productId": 123456, "quantity": 100}'
Output-
{
"success": "true"
}
HTTPS module
Node.js offers HTTP and HTTPS modules in its standard library to make HTTP/HTTPS API calls. To start transferring the data over HTTPS, you need to include the HTTPS module. This module will further create the Node HTTPS server that will listen to the server ports to generate the response to their clients.
const https = require(‘https’);
Well, it is known that HTTPS requests are secured. So it would help if you also created SSL certificates (self-signed), ensuring secured communication. Here, we are skipping this part.
Here, we are using the fundamental example showing the usage of the HTTPS module to carry out the GET call.
For example-
const https = require('https');
https.get('https://jsonplaceholder.typicode.com/users', res => {
let data = [];
const headerDate = res.headers && res.headers.date ? res.headers.date : 'no response date';
console.log('Status Code:', res.statusCode);
console.log('Date in Response header:', headerDate);
res.on('data', chunk => {
data.push(chunk);
});
res.on('end', () => {
console.log('Response ended: ');
const users = JSON.parse(Buffer.concat(data).toString());
for(user of users) {
console.log(`Got user with id: ${user.id}, name: ${user.name}`);
}
});
}).on('error', err => {
console.log('Error: ', err.message);
});
Output-
-> nodejs-requests git:(master) node native-https.js
Status Code: 200
Date in Response header: Sun, 10 Jan 2021 22:47:23 GMT
Response ended:
Got user with id: 1, name: Leanne Graham
Got user with id: 2, name: Ervin Howell
Got user with id: 3, name: Clementine Bauch
Got user with id: 4, name: Patricia Lebsack
Got user with id: 5, name: Chelsey Dietrich
Got user with id: 6, name: Mrs. Dennis Schulist
Got user with id: 7, name: Kurtis Weissnat
Got user with id: 8, name: Nicholas Runolfsdottir V
Got user with id: 9, name: Glenna Reichert
Got user with id: 10, name: Clementina DuBuque
-> nodejs-requests git:(master)
We will see what happens in the above code step by step. At first, we imported the HTTPS module using the required function. You will get this module with the installation of Node.js, so there is no need to create any json file or install anything to run this code.
Then we made a call to the JSONPlaceholder URL using the get method. The GET method has a callback that will respond to the res variable.
Then we initialize the data as an empty array and then use the log to display the status code and date from the response's header. After receiving the answer, the data will be stored in the data array.
Then we used the concat function to concat the array data and change it into a string. Then we have parsed the JSON to get the username and ID of the 10 users.
Axios Module
Axios is another popular JavaScript, promise-based Node.Js library. You can use this module on all modern browsers, and its tremendous support for IE8 and above. It is also used for making HTTP requests that can seamlessly work in both Browser and Node.js platforms.
Using Axios can be more advantageous over the native Fetch API:
- It supports the older browsers.
- It can quickly abort a request.
- It can set a response timeout.
- It comes with a built-in CSRF protection.
- It also supports the upload progress.
- It performs an automatic JSON data transformation.
To use the Axios module in your code, you need to install it using the following command from the terminal.
npm install --save axios
In the below-mentioned example, we are call the users JSON API using Axios.
const axios = require('axios');
//Axios get body
axios.get('https://jsonplaceholder.typicode.com/users')
.then(res => {
const headerDate = res.headers && res.headers.date ? res.headers.date : 'no response date';
console.log('Status Code:', res.status);
console.log('Date in Response header:', headerDate);
const users = res.data;
for(user of users) {
console.log(`Got user with id: ${user.id}, name: ${user.name}`);
}
})
.catch(err => {
console.log('Error: ', err.message);
});
Due to its promise-based nature, it will require less very evident code. Also, you can turn this code into the async/await format whenever needed. To use the axios body, you need to import it using the required function. Then, we used the axios.get (promise-based method) to call the JSONPlaceholder users API.
Then, with the help of the “then” method, we have received the requested data and have used the res variable to get the response object. Then, using the log function, we have displayed the status code and date from the response header.
The JSON data will be received as an array with res. data due to the feature of auto transformations. Also, we run the loop through the users to get their ID and their name.
The above example is for Axios get. Now, we will see the example for Axios post. With Axios, you can make post requests using the “post” data to a given endpoint that will trigger the desired events. To carry out an HTTP POST request in Axios, you must call the axios.post(). While you make a POST request, you need to use two parameters: the URI of the service endpoint and an object containing properties that you want to send to the Node HTTP server.
For example-
// Axios post body–POST request
axios({
method: 'post',
url: '/login',
data: {
firstName: 'Finn',
lastName: 'Williams'
}
});
Got Module
Node.js offers another sound and commonly used HTTP request library, Got. It was introduced as a lightweight alternative to the Request mentioned above module (now deprecated). By default, GOT will not parse the JSON. This is why we have added the {json: true} as an argument in the below code to include the JSON parsing.
Like Axios, GOT is also a promise-based API, making it more popular among Node.js developers.
To use the Got module, you need to import it using the required function below.
npm install --save got
In the below example, we have used the Got module to get the users from the mock API.
const got = require('got');
got.get('https://jsonplaceholder.typicode.com/users', {responseType: 'json'})
.then(res => {
const headerDate = res.headers && res.headers.date ? res.headers.date : 'no response date';
console.log('Status Code:', res.statusCode);
console.log('Date in Response header:', headerDate);
const users = res.body;
for(user of users) {
console.log(`Got user with id: ${user.id}, name: ${user.name}`);
}
})
.catch(err => {
console.log('Error: ', err.message);
});
If you look closely at an example, you will see that the above code is somehow similar to the Axios code but with the below-mentioned differences.
- To specify the response in the JSON format, you need to pass a second parameter explicitly- {responseType: 'json'}.
- Also, there is a difference in the status code header, which is mentioned as status.
Check out KnowldgeHut’s Node.js courses to know more.
SuperAgent Module
SuperAgent is one of the oldest and most popular modules of Node.js introduced by VisionMedia in 2011. SuperAgent is well-known as a progressive, client-side HTTP request library. You can use this module to support high-level HTTP client features. You can use it for both callback and promise-based APIs. This module is rich in plugins that can help tasks like no-cache, HTTP timings, etc.
Using the SuperAgent module, you need to import it using the following command.
npm install --save superagent
In the following example, we will be using the async/await to make the API call.
const superagent = require('superagent');
(async () => {
try {
const res = await superagent.get('https://jsonplaceholder.typicode.com/users');
const headerDate = res.headers && res.headers.date ? res.headers.date : 'no response date';
console.log('Status Code:', res.statusCode);
console.log('Date in Response header:', headerDate);
const users = res.body;
for(user of users) {
console.log(`Got user with id: ${user.id}, name: ${user.name}`);
}
} catch (err) {
console.log(err.message); //can be console.error
}
})();
Let’s see what is happening in the above example.
First, we have used the superagent library using the required function. Then, we used the IIFE with async as we used the await.
Next, we have added the try block and call the superagent. get with await, whose purpose is to resolve the promise and generate the response of HTTP calls. Then using the res variable, we got the date from res.headers. Using the log function, we display the status and date on the console.
Then, we have used the “user” constant to store the generated response and looped through that array of 10 users to get their username and ID. Then the following catch block will check for any occurred errors and manage them by displaying the error message on the console.
You can say that the SuperAgent module is reliable as it is thoroughly tested using SuperTest (Node.js library).
Node-fetch
Node-fetch is another HTTP request library for Node.js. Due to node-fetch, you do not have to implement the XMLHttpRequest in Node.js to run browser-specific Fetch polyfill. You can consider the node.fetch as a minimal code for the window.fetch compatible API on Node.js runtime.
For using the node.fetch in your code, you need to import it using the following code.
npm install node-fetch
We will call our mock users API using the node in the code below.fetch module.
const fetch = require('node-fetch');
(async () => {
try {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
const headerDate = res.headers && res.headers.get('date') ? res.headers.get('date') : 'no response date';
console.log('Status Code:', res.status);
console.log('Date in Response header:', headerDate);
const users = await res.json();
for(user of users) {
console.log(`Got user with id: ${user.id}, name: ${user.name}`);
}
} catch (err) {
console.log(err.message); //can be console.error
}
})();
Let’s see how the above code is different from the code with SuperAgent using the await/async.
- With fetch, you will not require an explicit GET method, and you can add the method key in the second parameter to send the HTTP verb.
- Also, we used the get method to get the header values. We called res.headers.get('date') to retrieve the value of the date response header.
- We used await res.json()to unwrap a promise to get the body as JSON.
HTTP Delete Request
You can use the HTTP delete body for deleting the specific resources. Below is the example of http delete request body nodejs that will delete request API calls. Let’s see the complete process.
- Create Node App:
mkdir my-request-app
cd my-request-app
npm init - Install Axios:
npm install axios --save
server.js
const axios = require('axios');
axios.delete('https://reqres.in/api/users/2')
.then((res) => {
console.log(`Status: ${res.status}`);
}).catch((err) => {
console.error(err);
}); - Run App
node server.js - Output
- Status: 201
Unlock your coding potential with our unique programming certification course. Gain the skills you need to excel in the tech industry. Enroll now!
Conclusion
We have used basic examples to explain the concept. But this is not all, as it has an extensive scope and does not end here. With this article, you will understand how you can make the HTTP request differently. Node.js has a comprehensive library with different functions and modules to make your every step and process more accessible.
So, if you have gone through this article, you must understand how every method is slightly different from the other. So, it might not be challenging to get along even for beginners.