If you are developing a node js project you may need to call third party REST APIs or internal REST APIs from your application.
There are many options available to make these calls.
Node JS provides its own https module for the same.
And we have the more elegant Axios library which you need to install separately.
Here are the differences between these two options.
Axios is much better in capability than Node js http module as evident from these differences:
API style:
The https
module uses a callback-based API, while Axios uses a promise-based API. This means that the https
module requires you to pass a callback function as an argument to the function that makes the HTTP request, while Axios returns a promise that you can use to handle the response asynchronously.
// https module (callback-based API)
const https = require('https');
function callAPI() {
https.get('https://example.com/restapi', (res) => {
res.setEncoding('utf8');
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(data);
});
});
}
// Axios (promise-based API)
const axios = require('axios');
function callAPI(){
try {
const response = await axios.get('https://api.example.com/endpoint');
console.log(response.data);
} catch (error) {
console.error(error);
}
};
Cancellation:
Axios provides built-in support for cancelling requests, which is not available in the https
module.
// Axios (cancellation supported)
const axios = require('axios');
function test() {
const source = axios.CancelToken.source();
setTimeout(() => {
source.cancel();
}, 1000);
try {
const response = await axios.get('https://api.example.com/endpoint', {
cancelToken: source.token,
});
console.log(response.data);
callback(null, {});
} catch (error) {
if (axios.isCancel
In this example, a cancel token is created using the axios.CancelToken.source
function. The cancel token is passed to the Axios request as an option. Then, a timer is set to cancel the request after 1 second.
When the request is cancelled, the promise returned by the Axios request is rejected with a Cancel
object. The error is caught in the catch block, and the axios.isCancel
function is used to check if the error is a Cancel
object. If it is, a message is logged to the console. If it is not, the error is logged and passed to the callback function.
Request and response transformation:
Axios allows you to transform the request and response data using functions, which is not possible with the https
module
// Axios (request and response transformation)
const axios = require('axios');
function test(){
const options = {
transformRequest: [(data) => JSON.stringify(data)],
transformResponse: [(data) => JSON.parse(data)],
};
try {
const response = await axios.post(
'https://api.example.com/endpoint',
{ name: 'John' },
options
);
console.log(response.data);
} catch (error) {
console.error(error);
}
};
Automatic retries:
Axios has built-in support for automatically retrying failed requests, which is not available in the https
module.
// Axios (automatic retries)
const axios = require('axios');
function retry() {
const options = {
retry: 3,
retryDelay: (retryCount) =>
* 1000,
};
try {
const response = await axios.get('https://api.example.com/endpoint', options);
console.log(response.data);
} catch (error) {
console.error(error);
}
};
The above code makes 3 retries if the API call fails , with a time difference of 1000,2000 and 3000 milliseconds between successive retries .
Browser support:
Axios can be used in the browser as well as in Node.js, while the https
module is only available in Node.js.
Here is a javascript example of axios code on the browser(front end):
// Axios (browser support)
import axios from 'axios';
export const myFunction = async () => {
try {
const response = await axios.get('https://api.example.com/endpoint');
console.log(response.data);
} catch (error) {
console.error(error);
}
};
Error handling:
Axios provides a consistent error handling mechanism, with HTTP errors being thrown as JavaScript exceptions, while the https
module requires you to check the status code of the response manually.
// Axios (consistent error handling)
const axios = require('axios');
function test(){
try {
const response = await axios.get('https://api.example.com/endpoint');
console.log(response.data);
} catch (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error(error.response.data);
console.error(error.response.status);
console.error(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.error(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.error('Error', error.message);
}
console.error(error.config);
}
};
That’s it!
Leave a Reply