Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios middleware to use in all instances of axios

I'm using axios in my react app using import axios from 'axios in many of my scripts. I want to use sort of a middleware that is invoked for all axios calls/errors. How do I approach this?

like image 616
Shakil Ahmed Avatar asked Nov 12 '18 06:11

Shakil Ahmed


1 Answers

As per the documentation - You need to create a file i.e

// api-client.js

import axios from 'axios';

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    console.log(config);
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

export default axios;

Then from your container or controller, import above file:

// Home.js
import apiClient from './api-client.js';
like image 155
Fazal Rasel Avatar answered Oct 24 '22 23:10

Fazal Rasel