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
相关产品推荐
相关产品推荐

