import axios from 'axios'
import {
message,
getStore
} from '@/config/utils'
import router from '@/router'
import store from '@/store'
let baseURL =
process.env.NODE_ENV === 'development' ?
'api' :
process.env.VUE_APP_BASE_URL
let reqList = []
const stopRepeatRequest = function (reqList, url, cancel, errorMessage) {
const errorMsg = errorMessage || ''
for (let i = 0; i < reqList.length; i++) {
if (reqList[i] === url) {
cancel(errorMsg)
return
}
}
reqList.push(url)
}
const allowRequest = function (reqList, url) {
for (let i = 0; i < reqList.length; i++) {
if (reqList[i] === url) {
reqList.splice(i, 1)
break
}
}
}
const instance = axios.create({
baseURL,
timeout: 10000
})
instance.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded;charset=UTF-8'
instance.interceptors.request.use(
config => {
let cancel
config.cancelToken = new axios.CancelToken(function (c) {
cancel = c
})
stopRepeatRequest(reqList, config.url, cancel, `${config.url} 请求被中断`)
const token = getStore('token')
token && (config.headers.token = token)
return config
},
error => {
return Promise.error(error)
}
)
instance.interceptors.response.use(
response => {
setTimeout(() => {
allowRequest(reqList, response.config.url)
}, 1000)
if (response.data.code === 1) {
return response.data.data
} else {
handleCode(response.data)
return Promise.reject(response.data)
}
},
error => {
if (axios.isCancel(error)) {
console.log(error.message)
} else {
setTimeout(() => {
allowRequest(reqList, error.config.url)
}, 1000)
}
handleCode({code: error.response.status})
return Promise.reject(error.response)
}
)
function handleCode(data) {
switch (data.code) {
case 0:
message.error(data.message || '网络错误')
break
case 401:
store.commit('loginOut')
router.replace({
path: '/login',
query: {
redirect: router.currentRoute.fullPath
}
})
break
case 403:
store.commit('loginOut')
router.replace({
path: '/login',
query: {
redirect: router.currentRoute.fullPath
}
})
break
default:
break
}
}
export function get(url, params) {
return instance.get(url, {
params: params
})
}
export function post(url, params) {
return instance.post(url, params)
}
export function del(url, params) {
return instance.delete(url, {
params: params
})
}
export function put(url, params) {
return instance.put(url, params)
}