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

Nuxt3对接Laravel Sanctum:API数据获取及CSRF Cookie问题求助

解决Laravel Sanctum + Nuxt3接口调用失败问题

1. 先确认Laravel端核心配置

  • 在.env中设置SANCTUM_STATEFUL_DOMAINS为你的Nuxt3域名,本地开发示例:SANCTUM_STATEFUL_DOMAINS=localhost:3000
  • 修改config/cors.php:
    return [
        'paths' => ['api/*', 'sanctum/csrf-cookie'],
        'allowed_origins' => ['http://localhost:3000'], // 替换为你的Nuxt域名
        'allowed_methods' => ['*'],
        'allowed_headers' => ['*'],
        'supports_credentials' => true,
    ];
    
  • 确保config/sanctum.php的stateful数组包含Nuxt域名

2. 修复Nuxt3获取CSRF Cookie失败问题

在nuxt.config.ts中配置代理和跨域凭证:

export default defineNuxtConfig({
  nitro: {
    devProxy: {
      '/api': {
        target: 'http://localhost:8000', // 替换为你的Laravel地址
        changeOrigin: true,
        prependPath: true
      },
      '/sanctum': {
        target: 'http://localhost:8000',
        changeOrigin: true,
        prependPath: true
      }
    }
  }
})

然后用useFetch带凭证请求CSRF Cookie:

async function getCsrfCookie() {
  await useFetch('/sanctum/csrf-cookie', {
    credentials: 'include',
    headers: { 'Accept': 'application/json' }
  })
}

3. 正确调用/api/categories接口

先获取CSRF Cookie,再携带XSRF-Token发起请求:

async function fetchCategories() {
  await getCsrfCookie()
  const { data, error } = await useFetch('/api/categories', {
    credentials: 'include',
    headers: {
      'X-XSRF-TOKEN': useCookie('XSRF-TOKEN').value
    }
  })
  if (error.value) console.error(error.value)
  return data.value
}

4. 替代方案:用Nuxt内置$fetch替代Axios

在plugins/fetch.client.ts中配置全局拦截器:

export default defineNuxtPlugin(() => {
  $fetch.create({
    credentials: 'include',
    async onRequest({ options }) {
      const xsrfToken = useCookie('XSRF-TOKEN').value
      if (xsrfToken) {
        options.headers = options.headers || {}
        options.headers['X-XSRF-TOKEN'] = xsrfToken
      }
    }
  })
})

之后直接调用接口:

const categories = await $fetch('/api/categories')

常见排查点

  • 查看浏览器Network面板,确认/sanctum/csrf-cookie返回204且Set-Cookie生效
  • 确保Laravel的Session驱动不是array(本地开发建议用file)
  • 检查跨域请求是否携带了withCredentials标识

内容的提问来源于stack exchange,提问作者patryk Dąbrowski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:35:19