You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Axios拦截器中登录页401重复跳转的问题?

解决Axios拦截器登录页401重复跳转问题

你可以通过以下几种方式实现登录页收到401状态码时跳过跳转:

方案一:判断当前路由是否为登录页

在跳转前检查当前路由路径,若已经处于登录页则不执行跳转操作:

axios.interceptors.response.use(
    (response) => {
        return response.data;
    },
    (error) => {
        if (error?.response?.status === 401) {
            // Vue Router 3.x 用 Router.currentRoute.path,4.x 用 Router.currentRoute.value.path
            const currentPath = Router.currentRoute.value.path;
            if (currentPath !== '/login') {
                Router.push('/login');
            }
        }

        return Promise.reject(error);
    },
);

方案二:判断请求接口是否为登录接口

从请求配置中获取接口URL,若为登录接口则跳过跳转:

axios.interceptors.response.use(
    (response) => {
        return response.data;
    },
    (error) => {
        if (error?.response?.status === 401) {
            // 假设登录接口路径包含'/api/login',可根据实际接口路径调整
            const requestUrl = error.config.url;
            if (!requestUrl.includes('/api/login')) {
                Router.push('/login');
            }
        }

        return Promise.reject(error);
    },
);

方案三:给登录请求添加自定义标识

发起登录请求时添加自定义配置项,拦截器中检测该配置决定是否跳转:

发起登录请求的代码:

// 在登录请求中添加自定义配置skipRedirect
axios.post('/api/login', { username: 'xxx', password: 'xxx' }, {
    skipRedirect: true
});

修改后的拦截器代码:

axios.interceptors.response.use(
    (response) => {
        return response.data;
    },
    (error) => {
        if (error?.response?.status === 401) {
            // 检查请求是否携带跳过跳转的标识
            const skipRedirect = error.config?.skipRedirect;
            if (!skipRedirect) {
                Router.push('/login');
            }
        }

        return Promise.reject(error);
    },
);

以上三种方案可按需选择:

  • 方案一适合单一登录页场景,逻辑简单直接
  • 方案二适合接口路径区分清晰的情况,无需依赖路由判断
  • 方案三灵活性最高,可精准控制任意请求是否跳过跳转

内容的提问来源于stack exchange,提问作者Epple

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 23:15:29