axios拦截器的使用

src etwork equest.js

import axios from 'axios'
//创建一个叫request的实例
export function request(config) {
   //1 创建实例
   const instance = axios.create({
     baseURL:'http://123.207.32.32:8000',
     timeout:5000
   })
   //2 拦截器
  //2.1请求拦截
  instance.interceptors.request.use(config=>{
    //console.log(config) //发送成功
    //请求拦截的作用
    //1 如果发送请求 不符合浏览器的某些要求,我们在这里进行某些操作 比如说 添加某些特殊的header、
    //2 比如每次发送网络请求时,都希望在界面中显示一个请求的图片(转啊转的那种)
    //3 某些网络请求(比如登录 token) 必须携带一些特殊的信息 如果没有携带 就拦截 跳转到登录的地方
    return config       //如果不返回 config会被拦截
  },err=>{
    //console.log(err)    //发送失败
    return err
  })
  //响应拦截
  instance.interceptors.response.use(res=>{
    //console.log(res);
    //res会返回一堆东西,但我们真正需要的是res.data
    return res.data;
  },err=>{
    console.log(err);
    return err;
  })
   //3 发送网络请求
   //为什么 instance 可以直接调.then
   //因为AxiosInstance的返回值本身就是一个Promise 只要直接return就可以了
   return instance(config)
}
原文地址:https://www.cnblogs.com/polax/p/13277148.html