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

Laravel Sanctum+React SPA登录重定向后触发CORS错误排查

问题描述

我已查阅各类社区帖子与技术教程,始终无法解决当前问题:我判断登录流程本身可正常执行,但等待登录完成重定向到用户列表页时触发CORS error。由于问题表现和我查阅到的其他案例存在差异,我不确定是否遗漏了配置项;我已对照LARAVEL SANCTUM DOCs检查后端配置,未发现明显错误。

控制台报错(CONSOLE)

控制台报错截图

Kernel.php中间件配置

class Kernel extends HttpKernel
{
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];
}

CORS.php跨域配置

'paths' => ['api/*', 'login', 'logout', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,

.env环境变量配置

SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN="localhost:8000"
SANCTUM_STATEFUL_DOMAINS=localhost:3000,127.0.0.1:3000

index.jsx Axios全局配置

axios.defaults.baseURL = 'http://localhost:8000/';
axios.defaults.withCredentials = true;
// axios.defaults.headers = {Accept: 'application/json'}
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers.post['Content-Type'] = 'application/json';

Login.jsx登录提交逻辑

const submit = async (e: SyntheticEvent) => {
    e.preventDefault();
    
    const response = await axios.get('/sanctum/csrf-cookie').then(response => {
        axios.post('/api/login',{
            email,
            password
        },{
            xsrfHeaderName: "X-XSRF-TOKEN", // change the name of the header to "X-XSRF-TOKEN" and it should works
            withCredentials: true
        }).then(response => {
            setRedirect(true);
        })
    });
}

if(redirect){
    return <Navigate to="/" />;
}

Wrapper.jsx路由全局包裹组件

该组件包裹所有业务页面,已尝试多种配置组合,问题仍复现。

const Wrapper = (props: any) => {
    const [redirect, setRedirect] = useState(false);
    const [user, setUser] = useState({
        last_name:'none'
    });

    //Here we render the page and then we fetch the current user
    // useEffect with []
    useEffect(() => {
        (
            async () => {
                try {
                    // const {data} = await axios.get('/api/user');

                    const {data} = await  axios.get('/api/user', {
                            xsrfHeaderName: "X-XSRF-TOKEN", // change the name of the header to "X-XSRF-TOKEN" and it should works
                            withCredentials: true
                        });

                    console.log("USER",data);

                } catch (e) {
                    console.log("e",e);
                    setRedirect(true);
                }
            }
        )();
    },[]);

    if(redirect){
        return <Navigate to="login" />;
    }

    return (
        <>
            <Nav/>

            <div className="container-fluid">
                <div className="row">
                    <Menu/>
                    <main className="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                        {props.children}
                    </main>
                </div>
            </div>
        </>
    )

}

export default Wrapper

Cookie信息(COOKIES)

Cookie信息截图


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 09:48:12