需求:项目中遇到接口判断用户是否有登陆态,如果没有,后端会重定向到登陆页
实际:请求接口返回302重定向,后端返回的登陆页也是302,不会显示出登陆页,因为当前页面的url为当前的页面,没有转到登陆页,需要前端判断将当前页面url改为登陆页的url
如何做:拦截axios请求
import axios from 'axios';
import { isObject } from 'lodash';
axios.interceptors.request.use(
config => config,
error => {
Promise.reject(error);
},
);
/* eslint consistent-return: off */
// respone拦截器
axios.interceptors.response.use(
response => {
//看网上文章,这里可以根据response的状态码来作区分,比如302跳转登陆页,4xx没权限跳转哪里,但是不知道为什么我拦截出来的status都是200,应该为302啊,大佬说应该是后端设置的?目前还不清楚,暂时先根据有没有返回内容来判断,有时间再研究一下,先mark
if (!isObject(response.data)) {
window.location.href = `xxx?redirectUrl=${encodeURIComponent('xxx')}`;
} else {
return response;
}
},
error => Promise.reject(error),
);
export default axios;