How to use the Node.js axios library for making HTTP requests with interceptors for request/response

  Arif Babu

         

  NodeJS



Image not found!!

Using Axios with interceptors for requests and responses in a Node.js application allows you to globally intercept and manipulate HTTP requests and responses. Here's how you can achieve this:

  1. Install Axios:

    First, you need to install Axios. You can do this via npm or yarn:

    npm install axios

    or

    csharp
    yarn add axios
  2. Create Interceptors:

    Axios allows you to create interceptors for both requests and responses. Interceptors are functions that Axios calls for each request or response, allowing you to intercept and modify them.

    javascript
    // axios-interceptors.js const axios = require('axios'); // Create an instance of Axios const instance = axios.create(); // Request interceptor instance.interceptors.request.use( function(config) { // Do something before request is sent console.log('Request sent:', config); return config; }, function(error) { // Do something with request error return Promise.reject(error); } ); // Response interceptor instance.interceptors.response.use( function(response) { // Do something with response data console.log('Response received:', response); return response; }, function(error) { // Do something with response error return Promise.reject(error); } ); module.exports = instance;
  3. Use Axios with Interceptors:

    Now, you can use Axios throughout your application with the configured interceptors.

    javascript
    const axios = require('./axios-interceptors'); // Make a GET request axios.get('https://api.example.com/data') .then(response => { console.log('Data:', response.data); }) .catch(error => { console.error('Error:', error); }); // Make a POST request axios.post('https://api.example.com/data', { /* data */ }) .then(response => { console.log('Data:', response.data); }) .catch(error => { console.error('Error:', error); });

    Axios will now log details of each request and response due to the interceptors.

With this setup, Axios will intercept all requests and responses, allowing you to log or modify them as needed. Adjust the interceptor logic according to your specific requirements, such as adding headers, handling errors, or logging.