axios接口错误拦截的封装
在main.js文件中书写以下代码,对登陆成功、未登录以及其他状态进行拦截,执行不同的操作
//根据前端的跨域方式做调整 (代理 直接用/api ,不同的请求-该vue.config.js)
// /a/b : /api/a/b => /a/b
axios.defaults.baseURL = '/api';
//超时设置
axios.defaults.timeout = 8000;
//接口错误拦截
axios.interceptors.response.use(function(response){
let res = response.data;//获取接口返回值
let path = location.hash;//获取路径 哈希路由
if(res.status == 0){//请求成功
return res.data;
}else if(res.status == 10 ){//未登录
if(path != '#/index'){//不为首页时才进行跳转 首页还能正常访问 不进行跳转
window.location.href = '/#/login';
}
return Promise.reject(res);
}else{
alert(res.msg);
return Promise.reject(res);
}
});