vue3项目开发中,在进行接口请求的时候,有鉴权,需要判断是否401,如果报401则跳转到登录页。
封装代码
import axios from 'axios'
import {devIp} from '@/api/ipConfig'
import router from "@/router/index";
const service = axios.create({
baseURL: devIp + '', // 测试IP
timeout: 100000, // request timeout
})
// request interceptor
service.interceptors.request.use(config => {
let token = localStorage.getItem('token')
if (token) {
config.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
}
return config
}, error => {
Promise.reject(error)
})
// respone interceptor
service.interceptors.response.use(
response => {
const res = response.data
if (res.code == 401) {
router.push({path: '/loginPage'});
}
return res;
},
error => {
if (error.response.data.code == 401) {
router.push({path: '/loginPage'});
}
return Promise.reject(error)
})
export default service