import axios from 'axios'
import router from '@/router'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// 创建axios实例
const service = axios.create({
baseURL: '/api', // url = base url + request url
timeout: 5000 // 请求超时
})
// 请求拦截器
service.interceptors.request.use(
(config) => {
// 发送请求前的操作
if (store.getters.token) {
// 让每个请求携带 token
// 请根据实际情况修改
config.headers.common['Authorization'] = getToken()//在请求头把token带上
}
return config
},
(error) => {
// 处理请求错误
console.log('请求错误', error) // for debug
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* 通过自定义代码确定请求状态
* 这里只是一个例子
* 您也可以通过HTTP状态代码来判断状态
*/
(response) => {
console.log(` ~ 响应数据:${response.config.url}`, response.data)
const res = response.data
// 如果code不是200,则判断为错误。
if (res.code !== 200) {
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
})
// 50008: 非法 token; 50012: 其他客户端已经登录; 50014: Token过期;
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// to re-login
MessageBox.confirm(
'You have been logged out, you can cancel to stay on this page, or log in again',
'Confirm logout',
{
confirmButtonText: 'Re-Login',
cancelButtonText: 'Cancel',
type: 'warning'
}
).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload()
})
})
}
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
(error) => {
const { response } = error
console.error('网络繁忙', response)
if (response) {
if (response.status == 401) {
router.push('/login')
store.dispatch('user/logout')
response.data = {
success: false,
errorMsg: '登录信息已过期,请您重新登录'
}
return response
}
return Promise.reject(
'由于网络繁忙,请求' + response.config.apiDesc + '有误,请稍后再试'
)
} else {
return Promise.reject('请求被中断')
}
}
)
换一篇写vue-element-admin封的接口请求逻辑