import axios from 'axios'
import Cookies from 'js-cookie'
import router from '@/router'
import qs from 'qs'
import isPlainObject from 'lodash/isPlainObject'
import { clearLoginInfo } from '@/utils'
import { Loading } from 'element-ui'
//开始加载动画
let loading;
function startLoading() {
loading = Loading.service({
lock:false, //是否锁定
text:'拼命加载中...',//加载中需要显示的文字
background:'rgba(0,0,0,.7)',//背景颜色
});
}
//结束加载动画
function endLoading() {
loading.close();
}
const http = axios.create({
timeout: 1000 * 180,
withCredentials: true
})
/**
* 请求拦截
*/
http.interceptors.request.use(config => {
// token
config.headers['token'] = Cookies.get('token')
// 默认参数
var defaults = {
'_t': new Date().getTime()
}
if (config.method === 'get') {
if (isPlainObject(config.params)) {
config.params = {
...defaults,
...config.params
}
}
} else if (config.method === 'post') {
startLoading();
if (isPlainObject(config.data)) {
config.data = {
...defaults,
...config.data
}
}
if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
config.data = qs.stringify(config.data)
}
}
return config
}, error => {
return Promise.reject(error)
})
/**
* 响应拦截
*/
http.interceptors.response.use(response => {
// setTimeout(() => {
// endLoading();
if(response.config.method=="post"){
endLoading();
}
if (response.data && response.data.code === 401) { // 401, token失效
clearLoginInfo()
router.replace({ name: 'login' })
}
return response
// },1000)
}, error => {
// setTimeout(() => {
if(error.config.method=="post"){
endLoading();
}
return Promise.reject(error)
// },1000)
})
export default http
07-25
4809