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

Laravel后端CORS配置问题:React带凭证跨域请求报错

Laravel API + React 登录请求CORS错误解决

问题场景

使用Laravel搭建后端API服务,前端React应用(地址http://127.0.0.1:3000)调用登录接口(http://magicsender.alresia.com/api/v1/auth/login)时,控制台抛出CORS错误:

Access to XMLHttpRequest at 'http://magicsender.alresia.com/api/v1/auth/login' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

相关代码

React登录组件

import { useRef, useState, useEffect, useContext } from 'react';
import AuthContext from "../../app/context/AuthProvider";

import axios from '../../app/api/axios';
const LOGIN_URL = '/auth/login';

const Login = () => {
const { setAuth } = useContext(AuthContext);
const userRef = useRef();
const errRef = useRef();

const [user, setUser] = useState('');
const [pwd, setPwd] = useState('');
const [errMsg, setErrMsg] = useState('');
const [success, setSuccess] = useState(false);

useEffect(() => {
    userRef.current.focus();
}, [])

useEffect(() => {
    setErrMsg('');
}, [user, pwd])

const handleSubmit = async (e) => {
    e.preventDefault();

    try {
        const response = await axios.post(LOGIN_URL,
            JSON.stringify({ user, pwd }),
            {
                headers: { 'Content-Type': 'application/json' },
                withCredentials: true
            }
        );
        console.log(JSON.stringify(response?.data));
        //console.log(JSON.stringify(response));
        const accessToken = response?.data?.accessToken;
        const roles = response?.data?.roles;
        setAuth({ user, pwd, roles, accessToken });
        setUser('');
        setPwd('');
        setSuccess(true);
    } catch (err) {
        if (!err?.response) {
            setErrMsg('No Server Response');
        } else if (err.response?.status === 400) {
            setErrMsg('Missing Username or Password');
        } else if (err.response?.status === 401) {
            setErrMsg('Unauthorized');
        } else {
            setErrMsg('Login Failed');
        }
        errRef.current.focus();
    }
}

return (
    <>
        {success ? (
            <section>
                <h1>You are logged in!</h1>
                <br />
                <p>
                    <a href="#">Go to Home</a>
                </p>
            </section>
        ) : (
            <section>
                <p ref={errRef} className={errMsg ? "errmsg" : "offscreen"} aria-live="assertive">{errMsg}</p>
                <h1>Sign In</h1>
                <form onSubmit={handleSubmit}>
                    <label htmlFor="username">Username:</label>
                    <input
                        type="text"
                        id="username"
                        ref={userRef}
                        autoComplete="off"
                        onChange={(e) => setUser(e.target.value)}
                        value={user}
                        required
                    />

                    <label htmlFor="password">Password:</label>
                    <input
                        type="password"
                        id="password"
                        onChange={(e) => setPwd(e.target.value)}
                        value={pwd}
                        required
                    />
                    <button>Sign In</button>
                </form>
                <p>
                    Need an Account?<br />
                    <span className="line">
                        {/*put router link here*/}
                        <a href="#">Sign Up</a>
                    </span>
                </p>
            </section>
        )}
    </>
 )
}
export default Login

Axios配置

import axios from 'axios';

export default axios.create({
    baseURL: 'http://magicsender.alresia.com/api/v1'
});

解决方案

错误核心:当请求携带凭证(withCredentials: true)时,CORS响应头Access-Control-Allow-Origin不能使用通配符*,必须指定具体的源地址。

Laravel端配置步骤

  1. 修改CORS配置文件
    打开config/cors.php,调整以下配置项:
  • 确保paths包含你的API路由前缀,例如'api/*'
  • 将allowed_origins设置为具体的前端地址:
    'allowed_origins' => [
        'http://127.0.0.1:3000',
        // 生产环境上线后添加正式前端域名
    ],
    
  • 确认supports_credentials设置为true:
    'supports_credentials' => true,
    
  1. 清除配置缓存
    在终端执行命令:
php artisan config:clear
  1. 验证中间件
    检查routes/api.php中的API路由组是否已应用cors中间件:
Route::prefix('v1')->middleware(['api', 'cors'])->group(function () {
    Route::post('auth/login', [AuthController::class, 'login']);
    // 其他API路由
});

额外说明

  • 不要修改前端withCredentials为false,登录请求需要携带凭证(如Cookie中的Token),否则后续接口鉴权会失效。
  • 生产环境部署时,记得将正式前端域名添加到allowed_origins列表中。

内容的提问来源于stack exchange,提问作者Fidelis E Peter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:56:03