Commit 2b399bb2 by 姜雷

修改请求方式

parent dd899331
import axios from 'axios'; import createBaseFetch from '../lib/Api';
import { Message, MessageBox } from 'element-ui';
import store from '../store';
import { SUCCESS_CODE, LOGOUT_CODE } from '@/config';
import { errorHandle } from './validate';
import { getYourIP } from '@/utils/getIp.js';
let ip = '127.0.0.1'; const fetch = createBaseFetch({
getYourIP(ipVal => { baseURL: process.env.VUE_APP_SYSTEM_SERVER_URL,
ip = ipVal;
});
// 创建axios实例
const service = axios.create({
baseURL: process.env.VUE_APP_SYSTEM_SERVER_URL, // api的base_url
timeout: 10000, timeout: 10000,
}); });
let logout = false;
// request拦截器
service.interceptors.request.use(
conf => {
const { notLoading } = conf;
store.dispatch('fetchStart', notLoading);
let token = store.getters.token;
console.error('token: ', token);
if (token) {
conf.headers = {
...conf.headers,
reqSource: 'pc',
token: token,
ip: ip,
};
} else {
conf.headers = {
...conf.headers,
reqSource: 'pc',
ip: ip,
};
}
return conf;
},
error => {
// Do something with request error
console.error(error); // for debug
Promise.reject(error);
}
);
// respone拦截器
service.interceptors.response.use(response => {
const res = response.data;
/**
* code为非'0'是抛错
*/
setTimeout(() => {
const { notLoading } = response.config;
store.dispatch('fetchDone', notLoading);
}, 500);
if (res.code !== SUCCESS_CODE) {
if (
response.headers &&
response.headers['content-type'] &&
/application\/octet-stream/.test(
response.headers['content-type'].toLowerCase()
)
) {
return response;
}
Message({
message: res.msg || '网络错误!',
type: 'error',
duration: 5 * 1000,
});
// -2:其他客户端登录了;Token 过期了;
if (res.code === LOGOUT_CODE) {
if (logout) return;
logout = true;
MessageBox.confirm(
'你已被登出,可以取消继续留在该页面,或者重新登录',
'确定登出',
{
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning',
}
)
.then(() => {
store.dispatch('FedLogOut').then(() => {
location.reload(); // 为了重新实例化vue-router对象 避免bug
});
})
.catch(err => {
console.error(err);
logout = false;
});
}
return Promise.reject(response.data);
} else {
return response.data;
}
}, errorHandle);
export default service; export default fetch;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment