在所有axios实例中使用的Axios中间件 [英] Axios middleware to use in all instances of axios

查看:778
本文介绍了在所有axios实例中使用的Axios中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在许多脚本中都使用import axios from 'axios在我的react应用程序中使用axios.我想使用一种针对所有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?

推荐答案

根据文档-您需要创建一个文件,即

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';

这篇关于在所有axios实例中使用的Axios中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆