axios设置请求拦截和响应拦截

首先我们先创建axios实例

const service = axios.create({
  baseURL: url, //是用于请求的服务器 URL
  timeout: 5000, // 请求超时时间 如果请求话费了超过 `timeout` 的时间,请求将被中断
  headers: {'X-Custom-Header': 'foobar'} // 自定义请求头
});

其他属性参考:https://www.kancloud.cn/yunye/axios/234845

接下来我们来添加拦截器

// 添加请求拦截器
service .interceptors.request.use(function (config) { // 在发送请求之前做些什么
  // 列如
  config.headers['usertoken'] = token;
return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
service .interceptors.response.use(function (response) { // 对响应数据做点什么 return response; }, function (error) { // 对响应错误做点什么 return Promise.reject(error); });

  假设你想移除拦截器

var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

  

原文地址:https://www.cnblogs.com/xiaocuncheng/p/10615142.html