axios请求拦截器和响应拦截器

293 阅读1分钟

1、请求拦截器 在请求发送前进行一系列操作,例如在每个请求体上加上token,统一做处理,以后要改也容易

axios.interceptors.request.use(function(config){

    //..在请求前做些什么,比如加token
    
    return config
    
},function(error){

    return Promise.reject(error)
    
})

2、响应拦截器 接收响应后进行一系列操作,例如服务器返回登陆状态失效,需要重新登陆,跳转到登录页

axios.interceptors.response.use(function(response){
    //接受响应做些什么,例如跳转到登录页
    ......
    return response;
    
},function(error){
    //对响应错误做点什么
    return Promise.reject(error)
})

3、移除拦截器

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