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

Laravel Sanctum部署后登录报错:Session store not set on request

问题:Laravel Sanctum + Nuxt.js 跨域登录报错 Session store not set on request

环境配置

Laravel 后端配置

  1. config/cors.php:
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'], 
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
  1. bootstrap/app.php:
->withMiddleware(function (Middleware $middleware) {
    $middleware->statefulApi();
})
  1. config/sanctum.php:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
    '%s%s',
    'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
    Sanctum::currentApplicationUrlWithPort()
))),
  1. 本地.env:
SANCTUM_STATEFUL_DOMAINS="is.test:9090"
  1. 生产环境后端.env:
SANCTUM_STATEFUL_DOMAINS="is.test:9090"

Nuxt.js 前端配置(nuxt.config.ts)

devServer: {
    port: 9090,
    host: "is.test",
},

问题现象

本地环境下前后端认证流程正常,但将Laravel后端部署到服务器后,本地Nuxt.js前端连接部署的后端时,登录请求抛出错误:Session store not set on request。

排查方向与解决方法

1. 修正生产环境后端的APP_URL配置

生产环境.env中必须设置正确的后端服务器域名/IP,例如:

APP_URL=https://your-production-domain.com

Sanctum的stateful配置会自动包含APP_URL对应的域名,若APP_URL配置错误,会导致Sanctum无法识别合法的会话请求,进而触发会话存储未设置的错误。配置后执行缓存清理命令:

php artisan config:cache
php artisan route:cache

2. 确认会话驱动的可用性

  • 若生产环境使用file会话驱动,检查storage/framework/sessions目录的读写权限,执行以下命令修复权限:
chmod -R 755 storage/framework/sessions
chown -R www-data:www-data storage/framework/sessions
  • 若使用redis等其他驱动,确保后端服务器与Redis服务连接正常,且相关配置(REDIS_HOST、REDIS_PORT等)正确。

3. 确保Nuxt.js请求携带凭证

在Nuxt.js的axios配置中开启withCredentials,确保跨域请求时携带会话Cookie:

// nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@nuxtjs/axios'],
  axios: {
    baseURL: 'https://your-production-domain.com/api',
    withCredentials: true
  }
})

同时,登录流程必须先请求/sanctum/csrf-cookie,再发送登录请求,两个请求都需携带凭证。

4. 验证Sanctum状态域配置

生产环境的SANCTUM_STATEFUL_DOMAINS需包含前端的完整域名(is.test:9090),同时确保配置未被缓存覆盖。执行以下命令清理Sanctum缓存:

php artisan sanctum:clear

5. 检查中间件顺序

确认statefulApi()中间件已正确注册,且会话中间件(StartSession)在API中间件组中生效。正常情况下statefulApi()会自动添加会话相关中间件,若仍有问题可手动检查app/Http/Kernel.php的api中间件组配置。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 12:40:13