import Vue from 'vue'
|
import axios from 'axios'
|
import Cookies from 'js-cookie'
|
import qs from 'qs'
|
import {clearLoginInfo} from '../utils'
|
import tip from '../utils/tips'
|
import isPlainObject from 'lodash/isPlainObject'
|
|
const http2 = axios.create({
|
baseURL: window.SITE_CONFIG['apiURL2'],
|
timeout: 1000 * 180,
|
withCredentials: true
|
})
|
|
/**
|
* 请求拦截
|
*/
|
http2.interceptors.request.use(config => {
|
config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN'
|
config.headers['token'] = Cookies.get('token') || ''
|
// 默认参数
|
var defaults = {}
|
// 防止缓存,GET请求默认带_t参数
|
if (config.method === 'get') {
|
config.params = {
|
...config.params,
|
...{'_t': new Date().getTime()}
|
}
|
}
|
if (isPlainObject(config.params)) {
|
config.params = {
|
...defaults,
|
...config.params
|
}
|
}
|
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)
|
})
|
|
/**
|
* 响应拦截
|
*/
|
http2.interceptors.response.use(response => {
|
if ((response.data.code === 401 || response.data.code === 10001)) {
|
clearLoginInfo()
|
Vue.prototype.$EventBus.$emit('reLogin')
|
return Promise.reject(response.data.msg)
|
}
|
let data = response.data
|
/*
|
data.success = data.code === 0
|
if (!data.success) {
|
tip.error(data.msg)
|
}
|
*/
|
return data
|
}, error => {
|
// console.error(error)
|
return Promise.reject(error)
|
})
|
|
export default http2
|