/**
* 全站http配置
*
* axios参数说明
* isSerialize是否开启form表单提交
* isToken是否需要token
*/
import axios from 'axios'
import querystring from 'querystring'; //格式转换
import store from '@/store/'; //vuex
import router from '@/router/router' //路由
import { serialize } from '@/util/tool' //表单序列化
import { getToken } from '@/util/tool' //获取全局token
import { Message } from 'element-ui' //el-ui的提示
import NProgress from 'nprogress' // 一个加载读条样式
import 'nprogress/nprogress.css' // progress bar style
axios.defaults.timeout = 10000;
//返回其他状态吗
axios.defaults.validateStatus = function (status) {
return status >= 200 && status <= 500; // 默认的
};
//跨域请求,允许保存cookie
axios.defaults.withCredentials = true;
//query参数编码
axios.defaults.paramsSerializer = function (params) {
return querystring.stringify(params);
};
// NProgress Configuration
NProgress.configure({
showSpinner: false
});
//HTTPrequest拦截
axios.interceptors.request.use(config => {
NProgress.start() // start progress bar
const meta = (config.meta || {});
const isToken = meta.isToken === false;
if (getToken() && !isToken) {
//config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
config.headers['accessToken'] = getToken()
}
//headers中配置serialize为true开启序列化
if (config.method === 'post' && meta.isSerialize === true) {
config.data = serialize(config.data);
}
return config
}, error => {
return Promise.reject(error)
});
//HTTPresponse拦截
axios.interceptors.response.use(res => {
NProgress.done();
const status = Number(res.status) || 200;
const statusWhiteList = [400] || [];
const message = res.data.message || 'Network error'; //后端返回的message
//如果在白名单里则自行catch逻辑处理
if (statusWhiteList.includes(status)) {
return Promise.reject(res);
}
//如果是401则跳转到登录页面
if (status === 401) {
router.push({ path: '/login' })); //并在这里做页面登出操作
}
// 如果请求为非200否者默认统一处理
if (status !== 200) {
Message({
message: message,
type: 'error'
})
return Promise.reject(new Error(message))
}
return res;
}, error => {
NProgress.done();
return Promise.reject(new Error(error));
})
export default axios;
表单序列化
//tool.js
export const serialize = data => {
let list = [];
Object.keys(data).forEach(ele => {
list.push(`${ele}=${data[ele]}`)
})
return list.join('&');
};