59 lines
1.5 KiB
JavaScript
59 lines
1.5 KiB
JavaScript
import axios from 'axios';
|
|
import qs from 'qs';
|
|
import cookie from 'vue-cookies';
|
|
import router from '../router/index.js';
|
|
|
|
let baseURL = import.meta.env.VITE_APP_BASE_URL + '/api';
|
|
|
|
let headers = {
|
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
};
|
|
|
|
const request = axios.create({
|
|
baseURL,
|
|
headers
|
|
});
|
|
|
|
// 添加请求拦截器
|
|
request.interceptors.request.use(
|
|
function (config) {
|
|
// 在发送请求之前做些什么
|
|
if (config.method == 'post' || config.method == 'POST') {
|
|
config.data = qs.stringify(config.data);
|
|
}
|
|
if (cookie.get('token') && cookie.get('token') != '') {
|
|
config.headers['Authorization'] = cookie.get('token');
|
|
}
|
|
return config;
|
|
},
|
|
async function (error) {
|
|
// 对请求错误做些什么
|
|
return error.message;
|
|
}
|
|
);
|
|
|
|
// 添加响应拦截器
|
|
request.interceptors.response.use(
|
|
function (response) {
|
|
// const msg = useMessage()
|
|
// 2xx 范围内的状态码都会触发该函数。
|
|
// 对响应数据做点什么
|
|
if (response.data.code == 9) {
|
|
window.$msg.error('登录过期,请重新登录');
|
|
router.push('/login');
|
|
return false;
|
|
}
|
|
if (response.data.code == 8) {
|
|
window.$msg.error(response.data.msg);
|
|
return false;
|
|
}
|
|
return response.data;
|
|
},
|
|
async function (error) {
|
|
// 超出 2xx 范围的状态码都会触发该函数。
|
|
// 对响应错误做点什么
|
|
return error.message;
|
|
}
|
|
);
|
|
export default request;
|