import axios from 'axios';
import qs from 'qs';
import { getCookies } from '@/util/index';
const request = axios.create({
// baseURL: process.env.BASE_URL,
timeout: 5000
});
// 拦截请求
request.interceptors.request.use(config => {
config.method === 'post' ?
(config.data = qs.stringify({...config.data })) :
(config.params = {...config.params });
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
if (config.url !== '/user/login') {
config.headers['authorization'] = getCookies('token');
}
if (!getCookies('token') && config.url !== '/user/login') {
window.location.href = '/login';
}
return config;
});
// 添加响应拦截
request.interceptors.response.use(
response => {
// 直接返回response.data
return response;
},
error => {
const { status, data } = error.response;
switch (status) {
case 401:
alert('登录失败,请重新登录');
break;
case 422:
alert(data.msg);
break;
default:
alert('请稍后重试');
}
}
);
export default request;
网友评论