vue项目axios拦截器

拦截器:发送或响应请求之前,做一些需要判断的事情,比如发送某些请求需要携带token,可在请求拦截器中配置token;响应某些请求后,需要对获取的数据进行解密或在请求前做一些其他操作。

具体实现如下:

添加拦截器

import axios from 'axios'
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前执行的操作
    // 过滤掉xxxx有关的请求接口
    // 配置token
    // 如果需要加密数据,则加密config.data
    return config;
}, function (error) {
    // 对请求错误执行的操作
    return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据执行的操作
    //如需要解密返回数据,则解密response.data
}, function (error) {
   // 对响应错误执行的操作
    return Promise.reject(error);
});
export default {
    install: (Vue, options) => {   
        Vue.prototype.Http = axios
    }
}

const Http = axios
export {Http}

请求数据

this.Http.post('/path',data).then(json => {
    if(json.returnCode == "0000"){
        //请求成功的操作...
    }else{
        //请求失败的操作...
    }
})
发布了58 篇原创文章 · 获赞 85 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/codezha/article/details/98626136