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

Laravel+Next.js应用登录后调用/api/user报401 Unauthorized错误

Laravel Sanctum + Next.js 401 Unauthorized 问题排查方案

1. 检查Laravel Sanctum核心配置

  • 确认.env文件中:
    • SESSION_DOMAIN设置为前后端共享的根域名(例:前后端分别为localhost:3000和localhost:8000时,设为localhost)
    • SANCTUM_STATEFUL_DOMAINS包含前端完整域名+端口,例如localhost:3000,127.0.0.1:3000
  • 检查config/cors.php:确保supports_credentials设为true(跨域请求需携带Cookie)
  • 检查config/sanctum.php:stateful数组需包含前端域名,与SANCTUM_STATEFUL_DOMAINS保持一致

2. 前端Axios配置修正

  • 全局开启withCredentials:Sanctum依赖Cookie传递会话信息,必须在Axios初始化时设置:
    import axios from 'axios';
    axios.defaults.withCredentials = true;
    axios.defaults.baseURL = 'http://localhost:8000'; // 替换为你的Laravel后端地址
    
  • 验证csrf()函数逻辑:确保它正确调用Laravel的/sanctum/csrf-cookie接口,获取并设置CSRF令牌Cookie,示例:
    export const csrf = () => axios.get('/sanctum/csrf-cookie');
    

3. 请求路径与代理问题

  • 修正登录请求路径:你的代码中axios.post('api/login', props)是请求前端Next.js的API路由,实际应请求Laravel后端的/login端点,改为:
    await axios.post('/login', props);
    
  • 若使用Next.js API路由代理后端请求(即/api/user是前端路由):
    • 在pages/api/user.js中确保代理请求携带Credentials:
      export default async function handler(req, res) {
        try {
          const response = await fetch('http://localhost:8000/api/user', {
            credentials: 'include',
            headers: {
              ...req.headers,
              'Content-Type': 'application/json',
            },
          });
          const data = await response.json();
          res.status(response.status).json(data);
        } catch (err) {
          res.status(500).json({ error: 'Failed to fetch user data' });
        }
      }
      
    • 在next.config.js中配置路由重写避免跨域:
      module.exports = {
        async rewrites() {
          return [
            {
              source: '/api/:path*',
              destination: 'http://localhost:8000/api/:path*',
            },
          ];
        },
      };
      

4. 登录后数据刷新时机调整

当前代码中mutate()与router.push()同步执行,可能导致Cookie未被前端接收就发起请求,改为异步等待:

const login = async ({ setErrors, setStatus, ...props }) => {
  await csrf();
  setErrors([]);
  setStatus(null);
  try {
    await axios.post('/login', props);
    await mutate(); // 等待用户数据刷新完成
    router.push("/dashboard");
  } catch (error) {
    if (error.response.status !== 422) throw error;
    setErrors(error.response.data.errors);
  }
};

5. Laravel后端路由验证

确保/api/user路由正确使用auth:sanctum中间件,在routes/api.php中:

use Illuminate\Http\Request;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 06:40:26