import Vue from 'vue';
import router from '@/router';
import qs from 'qs';
// set axios default
// axios.defaults.withCredentials = true; // 跨域时若要发送cookies需设置该选项
//对axios配置基本路径、时长、请求头
axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
axios.defaults.timeout = 30 * 1000;
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
// request interceptor统一请求拦截器
axios.interceptors.request.use(
config => {
// do something before request is sent
return config;
},
error => {
// do something with request error
console.log(error); // for debug
return Promise.reject(error);
}
);
// response interceptor
axios.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/
response => {
window.loading && window.loading.close();
const data = response.data;
// if the custom code is not 200, it is judged as an error.
if (data.status_code !== 200) {
let msg = '';
if (data.errors) {
msg = Object.values(data.errors)[0][0];
} else {
msg = data.message;
}
if (data.status_code === 400) {
// console.log(990, router.currentRoute.path)
Vue.prototype.$message({
message: 'token失效,请重新登录!' || 'error',
type: 'error',
duration: 1 * 1000,
onClose: () => {
localStorage.removeItem('token');
window.location.href = '/login?redirect=' + router.currentRoute.path;
}
});
} else {
Vue.prototype.$message({
message: msg || 'error',
type: 'error',
duration: 2 * 1000
});
}
return Promise.reject(msg || 'error');
} else {
return data;
}
},
error => {
console.log('err' + error); // for debug
window.loading && window.loading.close();
Vue.prototype.$message({
message: '服务端错误',
type: 'error',
duration: 5 * 1000
});
return Promise.reject(error);
}
);
// 封装请求接口的方法
const http = function(url, data, method, source) {
let token = localStorage.getItem('token') ? localStorage.getItem('token') : '';
if (source) {
axios.defaults.baseURL = process.env[`VUE_APP_${source}_API`];
}
let options = {
url,
method,
data: {}
};
// 如果接口不为登录接口,就把token带上
if (url !== '/impower' && url !== '/sys-login') {
options.data = { token, ...data };
} else {
options.data = data;
}
if (options.method.toLowerCase() === 'get') {
options.params = options.data;
} else {
options.data = qs.stringify(options.data);
}
window.loading = Vue.prototype.$loading({
spinner: 'el-icon-loading',
background: 'rgba(300, 300, 300, 0.5)',
customClass: 'loading',
body: true
});
return axios(options);
};
export default http;
网友评论