In this tutorial, we’ll take a look at how to make an HTTP request in Node.js
As with a lot of other things with Node.js there are lots of different ways to make an HTTP request.
In this article, we’ll go through the two main options you have; either use the built in Node.js libraries or use an npm package.
Use built in functions to make an HTTP request in Node.js
For this we’ll use the https
module and it’s corresponding get
function.
const https = require('https');
https
.get('https://www.juniordevelopercentral.com', (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
console.log(data);
});
})
.on('error', (error) => {
console.log(error);
});
Note, you can use the http
module if you want to make a insecure request.
The way the get
function works in the above code is to take a function as the second argument which contains a response
object.
On this object, we can listen for events and we setup to listeners for data, where we append new data chunks to an empty string variable, and end when the request is completed.
Finally, we can listen for an error event on the outside of the get
function and deal with any errors if they occur.
Whilst this works, it can be simpler to use a prebuilt package to hide some of this complexity.
Use an NPM package to send an HTTP request in Node.js
There are lots of different packages we can use each with various features and issues.
I’m going to use the axios
package as it’s generally the standard one that’s used.
npm install axios
const axios = require('axios');
axios.get('https://www.juniordevelopercentral.com')
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
});
The nice thing about Axios is that it is Promise-based so we can make a get
request and use the .then()
and .catch()
properties to work with our result and any errors.