axios 全局拦截
程序员文章站
2022-03-11 21:56:47
import axios from 'axios'import { getToken } from './auth'const service = axios.create({ baseURL: process.env.VUE_APP_BASE_API, // 接口域名地址 timeout: 5000 // 请求超时时间})service.interceptors.request.use( config => { if (getToken()) {...
import axios from 'axios'
import { getToken } from './auth'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // 接口域名地址
timeout: 5000 // 请求超时时间
})
//请求拦截器(interceptors.requst)是指可以拦截每次或指定HTTP请求,并可修改配置项
service.interceptors.request.use(
config => {
if (getToken()) {
config.headers['X-Token'] = getToken()// 'token' token是在登录成功的时候才会给你 有的话加到请求头上
}
return config
},
error => {
console.log(error) // for debug
return Promise.reject(error)
}
)
//响应拦截器(interceptors.response)可以在每次HTTP请求后拦截住每次或指定HTTP请求,并可修改返回结果项
service.interceptors.response.use(
response => {
const res = response.data
if (res.code !== 20000) {
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
})
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
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 => {
console.log('err' + error)
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
本文地址:https://blog.csdn.net/weixin_45942049/article/details/108811987
上一篇: 13 - 文件上传保存路径的几种方案
下一篇: android 进程不死的方法