1.请求头中设置token
每次请求请求头都携带token,没有token或者token失效后端会返回错误
javascript
axios.interceptors.request.use(configs => {
let token = sessionStorage.getItem("token");
if (token) {
configs.headers.authorization = token;
}
}
2.拒绝非权限请求
防止一些在浏览器上强制将按钮改成可用(如将disabled改为true就可用),然后发起请求后发送后端
javascript
const actionMapping = {
'get': 'view',
'post': 'add',
'put': 'edit',
'delete': 'delete',
}
const whiteList = ['/login','/user/login','/user/me', '/', '/404']
// 对请求头进行处理(token)
axios.interceptors.request.use(configs => {
let token = sessionStorage.getItem("token");
if (token) {
configs.headers.authorization = token;
}
// 拒绝非权限请求
if (!whiteList.includes(configs.url)) {
let metaRights = router.currentRoute.value.meta.rights;
let action = actionMapping[configs.method];
if (!metaRights.includes(action)) {
ElMessage.error("没有操作权限");
return Promise.reject(new Error('没有操作权限'))
}
}
return configs;
});
3.响应拦截
响应控制:请求返回401,token无效或者后期,则需要跳转到登录界面
javascript
// 处理返回数据
axios.interceptors.response.use(response => {
return response;
}, error => {
let { status, data } = error.response;
let { message, errorDetail } = error.response.data;
....
if (status === 401 || status === 402 || status === 403) {
// 没有权限,需要重新登录
ElMessage.error("token失效或无权限,正跳转登录页面......");
sessionStorage.clear();
return router.push("/login");
}
....
}