北尚诉办前端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.9 KiB

6 years ago
import axios from 'axios'
import Cookies from 'js-cookie'
import router from '@/router'
3 years ago
import Vue from 'vue'
6 years ago
import qs from 'qs'
import { clearLoginInfo } from '@/utils'
import isPlainObject from 'lodash/isPlainObject'
3 years ago
var lastTime = null // 最后一次点击的时间
6 years ago
const http = axios.create({
baseURL: window.SITE_CONFIG['apiURL'],
timeout: 1000 * 180,
withCredentials: true
})
/**
* 请求拦截
*/
http.interceptors.request.use(config => {
3 years ago
if (lastTime) {
if (new Date().getTime() - lastTime > (30 * 60 * 1000)) {
Vue.prototype.$alert('停留时间过长', '请重新登录', {
confirmButtonText: '确定',
callback: action => {
clearLoginInfo()
router.replace({ name: 'login' })
}
})
}
}
lastTime = new Date().getTime()
6 years ago
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)
})
/**
* 响应拦截
*/
http.interceptors.response.use(response => {
if (response.data.code === 401 || response.data.code === 10001) {
clearLoginInfo()
router.replace({ name: 'login' })
return Promise.reject(response.data.msg)
}
return response
}, error => {
console.error(error)
return Promise.reject(error)
})
export default http