响应拦截器
// http response拦截器
axios.interceptors.response.use(
response => {
return response;
}, error => {
if (error.response) {
switch (error.response.status) {
case 401:
// 401 清除token信息并跳转到登录页面
// store.commit(types.LOGOUT);
router.replace({
path: '/login'
});
break;
case 4002:
Message.error({
message: '请求超时'
});
}
};
// console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
return Promise.reject(error.response);
});
// 调用接口方法封装
export function $http(opt) {
return axios({
method: opt.method || 'post',
baseURL: '/base/',
url: opt.url,
params: opt.data,
timeout: 10000,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Session-Id': sessionStorage.token,
'Content-Type': 'application/json; charset=UTF-8'
}
}).then(
(res) => {
if (res.data.state === 0) {
opt.success(res);
} else if (res.data.state === 1) {
opt.fail(res);
} else if (res.data.state === 2) {
// token 过期
this.tipInfo(res.data.desc, '提示', false, 'error', () => {
window.location.href = "/";
});
} else {
if (opt.fail) {
opt.fail(res);
}
}
}
);
}
使用
$http(obj);