import Vue from 'vue'
import axios from 'axios'
import {
baseURL,
contentType,
debounce,
invalidCode,
noPermissionCode,
requestTimeout,
successCode,
} from '@/config'
import store from '@/store'
import qs from 'qs'
import router from '@/router'
import { isArray } from '@/utils/validate'
let loadingInstance
const handleCode = (code, msg) => {
switch (code) {
case invalidCode:
Vue.prototype.$baseMessage(msg || `后端接口${code}异常`, 'error')
store.dispatch('user/resetAccessToken').catch(() => {})
if (loginInterception) {
location.reload()
}
break
case noPermissionCode:
router.push({ path: '/401' }).catch(() => {})
break
default:
Vue.prototype.$baseMessage(msg || `后端接口${code}异常`, 'error')
break
}
}
const instance = axios.create({
baseURL,
timeout: requestTimeout,
headers: {
'Content-Type': contentType,
},
})
instance.interceptors.request.use(
(config) => {
const token = store.getters['user/accessToken']
if (token) {
config.headers['Authorization'] = `Bearer ${token}`
}
if (config.data && config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8') config.data = qs.stringify(config.data)
return config
},
(error) => {
return Promise.reject(error)
}
)
instance.interceptors.response.use(
async (response) => {
const { data, config } = response
const { code, msg, Code } = data
console.log(data)
if (Code == 401) {
await store.dispatch('user/resetAccessToken')
router.push({ path: '/login', replace: true }).then(() => {})
return
}
const codeVerificationArray = isArray(successCode) ? [...successCode] : [...[successCode]]
if (codeVerificationArray.includes(code)) {
return data
} else {
handleCode(code, msg)
return Promise.reject('vue-admin-beautiful请求异常拦截:' + JSON.stringify({ url: config.url, code, msg }) || 'Error')
}
},
(error) => {
const { response, message } = error
console.log('response', response)
if (error.response && error.response.data) {
const { status, data } = response
handleCode(status, data.msg || message)
return Promise.reject(error)
} else {
let { message } = error
if (message.includes('timeout')) {
message = '后端接口请求超时'
}else{
message = '后端接口连接异常'
}
Vue.prototype.$baseMessage(message || `后端接口未知异常`, 'error')
return Promise.reject(error)
}
}
)
export default instance
import request from './request'
export function getList(params) {
return request({
url: `url`,
method: 'get',
params,
})
}