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

React请求Laravel遇419错误:CSRF令牌不匹配问题求助

React向Laravel发送POST请求始终报419错误(CSRF令牌不匹配)

我试了网上各种解决方案都没用,用React给Laravel发POST请求一直碰到419错误。以下是我的相关配置和代码:

cors.php配置

'paths' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,

获取CSRF Token的方法

const csrf = () => axios.get('http://localhost:8000/sanctum/csrf-cookie', {
  withCredentials: true,
} ).then((res) => console.log(res))

POST请求代码

await csrf();
axios.post(`http://localhost:8000/login`, payload, {
  headers: {
    "Content-Type": 'application/json',
    "X-XSRF-TOKEN": document.cookie.replace(/(?:(?:^|.*;\s*)XSRF-TOKEN\s*=\s*([^;]*).*$)|^.*$/, '$1'),
  },
  withCredentials: true,
  withXSRFToken: true,
  
})

我已经确认请求头里的令牌和浏览器Cookie完全一致,但还是提示CSRF令牌不匹配,相关截图:

  • 浏览器Cookie
  • 请求头中的CSRF令牌

内容的提问来源于stack exchange,提问作者Jaycie Dela Cruz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 11:03:12