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

React应用中无法跟随API返回的301跳转至Auth0登录界面问题

问题原因

React Router的<Navigate>是客户端路由导航,仅修改浏览器地址栏URL,不会触发浏览器向服务器发送/api/login的HTTP请求。而你的Express API返回的301重定向,需要浏览器发起真实请求才会生效,因此仅靠<Navigate>无法触发Auth0跳转,只有刷新页面时浏览器才会请求该路由,重定向才起作用。

解决方案

修改ProtectedRoute组件,用浏览器原生跳转替代React Router的<Navigate>,触发真实的API请求:

import { useLocation, Outlet } from 'react-router-dom';

interface ISession {
    userId: string;
    role: string;
    details: any;
}

type RouteProps = {
    children?: JSX.Element;
    session: ISession;
    loading: boolean;
};

const ProtectedRoute = ({ session, children, loading }: RouteProps) => {
  const location = useLocation();

  if (loading) return null;
  
  if (!!session.userId) {
    return children || <Outlet />;
  } else {
    // 拼接跳转目标参数到API登录路由
    const redirectUrl = encodeURIComponent(location.pathname);
    window.location.replace(`/api/login?redirectTo=${redirectUrl}`);
    // 返回null避免React渲染报错
    return null;
  }
};

export default ProtectedRoute;
补充说明
  • window.location.replace和<Navigate replace>行为一致,会替换当前历史记录,不会留下多余的跳转痕迹。
  • 原生跳转触发服务器/api/login请求后,浏览器会自动处理返回的301重定向,直接跳转到Auth0登录界面。
  • 开发环境下需确保React应用和Express API的代理配置正确,可在React项目的package.json中添加"proxy": "http://localhost:你的Express端口",让前端请求自动转发到API服务器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:51:20