rt-sim-training-client/src/utils/request.js

66 lines
1.9 KiB
JavaScript
Raw Normal View History

2019-07-02 16:29:52 +08:00
import axios from 'axios';
import store from '../store';
import { MessageBox } from 'element-ui';
import { handleToken, gainClientId } from '@/utils/auth';
2019-08-02 10:36:17 +08:00
import { getBaseUrl } from '@/utils/baseUrl';
import { EventBus } from '@/scripts/event-bus';
2019-07-02 16:29:52 +08:00
2019-08-02 10:36:17 +08:00
const BASE_API = getBaseUrl();
2019-07-02 16:29:52 +08:00
// 创建axios实例
const service = axios.create({
2019-08-02 10:36:17 +08:00
baseURL: BASE_API, // api的base_url
withCredentials: true, // 跨域请求时是否需要使用凭证
timeout: 60000 // 请求超时时间
2019-07-02 16:29:52 +08:00
});
// request拦截器
service.interceptors.request.use(config => {
2019-08-02 10:36:17 +08:00
if (handleToken()) {
config.headers['X-Token'] = handleToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
}
if (config.time) {
config.timeout = config.time; // 让每个请求携带自定义token 请根据实际情况自行修改
}
return config;
2019-07-02 16:29:52 +08:00
}, error => {
2019-08-02 10:36:17 +08:00
// Do something with request error
Promise.reject(error);
2019-07-02 16:29:52 +08:00
});
// respone拦截器
service.interceptors.response.use(
2019-08-02 10:36:17 +08:00
response => {
/** code为非200是抛错 可结合自己业务进行修改*/
const res = response.data;
if (res.code !== 200) {
// 50008:非法的token; 50012:其他客户端登录了; 50014:Token 过期了;
if (res.code === 40004 || res.code === 40005 || res.code === 40003) {
// eslint-disable-next-line no-undef
EventBus.$emit('stop');
// eslint-disable-next-line no-undef
EventBus.$emit('viewLoading', false);
// eslint-disable-next-line no-undef
EventBus.$emit('clearCheckLogin');
MessageBox.confirm('你已被登出,请重新登录', '确定登出', {
confirmButtonText: '重新登录',
showCancelButton: false,
type: 'warning'
}).then(() => {
store.dispatch('FedLogOut', gainClientId()).then(() => {
location.reload();// 为了重新实例化vue-router对象 避免bug
});
});
}
return Promise.reject(res);
} else {
return response.data;
}
},
error => {
return Promise.reject(error);
}
2019-07-02 16:29:52 +08:00
);
export default service;