文章目录
一、需求
用户登录后将 token 存储在下次接口访问的请求头中进行接口请求
二、分析
js
import router from './router';
import { Message } from 'element-ui';
import Axios from 'axios'
router.beforeEach((to, from, next) => {
if (to.path === '/login') {
next();
} else {
let token = localStorage.getItem('Token');
if (token === null || token === '') {
Message.warning('请登录')
next('/login');
} else {
next();
}
}
});
// 添加请求拦截器,在请求头中加token
Axios.interceptors.request.use(
config => {
if (localStorage.getItem('TOKEN')) {
config.headers.TOKEN = localStorage.getItem('TOKEN');
}
return config;
},
error => {
return Promise.reject(error);
});