In this tutorial, we will learn how to use Fetch and Axios for seamless API integration in Node.js. Both Fetch and Axios are popular libraries for making HTTP requests in Node.js, and they provide a simple and clean way to interact with APIs.
- Installing Fetch and Axios
Before we can use Fetch and Axios in our Node.js application, we need to install them as dependencies. To do this, run the following commands in your terminal:
npm install node-fetch --save
npm install axios --save
- Using Fetch
Fetch is a built-in global object in modern browsers that provides an interface for fetching resources. In Node.js, we can use thenode-fetch
library, which provides a similar API to the Fetch API in the browser.
To make a GET request using Fetch in Node.js, we can write the following code:
const fetch = require('node-fetch');
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
In this example, we are making a GET request to the JSONPlaceholder API and logging the response data to the console.
- Using Axios
Axios is a popular Promise-based HTTP client for the browser and Node.js. It provides a simple API for making HTTP requests and handling responses.
To make a GET request using Axios in Node.js, we can write the following code:
const axios = require('axios');
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => console.log(response.data))
.catch(error => console.error(error))
In this example, we are making a GET request to the JSONPlaceholder API using Axios and logging the response data to the console.
- Performing POST Requests
Both Fetch and Axios support other HTTP methods like POST, PUT, DELETE, etc. To perform a POST request using Fetch, we can write the following code:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
And to perform a POST request using Axios, we can write the following code:
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1,
})
.then(response => console.log(response.data))
.catch(error => console.error(error))
- Conclusion
In this tutorial, we have learned how to use Fetch and Axios for seamless API integration in Node.js. Both libraries provide a clean and simple API for making HTTP requests and handling responses. Fetch is a built-in global object in modern browsers, while Axios is a popular Promise-based HTTP client for both the browser and Node.js. By following the examples in this tutorial, you can easily integrate APIs into your Node.js applications using Fetch and Axios.