要求请求没响应前,不可重复同一请求
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '../router'
import { getToken } from '@/utils/auth'
let allowedRepeat = false // 请求还没响应时是否允许重复同一请求
let pending = {}
const CancelToken = axios.CancelToken
// 记录正在进行的请求
const removePending = (key, isRequest = false) => {
if (pending[key] && isRequest) {
pending[key]('Duplicate request')
}
delete pending[key]
}
// 生成key用以判断是否同一请求
const getRequestIdentify = config => {
const url = config.url
if (config.method === 'post') {
return encodeURIComponent(url + JSON.stringify(config.data))
}
return encodeURIComponent(url + JSON.stringify(config.params))
}
// create an axios instance
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 30000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
if (!allowedRepeat) {
const requestData = getRequestIdentify(config)
removePending(requestData, true)
config.cancelToken = new CancelToken((c) => {
pending[requestData] = c
})
}
if (store.getters.token) {
config.headers['Access-Token'] = getToken()
}
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data
if (res.code !== 200) {
if (document.getElementsByClassName('el-message').length <= 0) {
Message({
message: res.msg || 'Error',
type: 'error',
duration: 2 * 1000
})
}
// 登录过期
if (res.code === -2) {
return store.dispatch('user/logout').then(() => {
router.replace('/login')
})
}
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
error => {
let tip = error.message
if (error.message.indexOf('timeout') !== -1) {
tip = '请求超时'
}
if (error.message.indexOf('Network Error') !== -1) {
tip = '网络错误'
}
if (document.getElementsByClassName('el-message').length <= 0 && tip !== 'Duplicate request') {
Message({
message: tip,
type: 'error',
duration: 2 * 1000
})
}
return Promise.reject(error)
}
)
export default service