Nuxt useFetch页面重载时无法获取Cookie的问题排查
我在Nuxt中使用useFetch调用Express后端API,正常页面导航时请求能通过验证正常返回,但页面重载时API调用直接失败。移除Express路由的checkTokenMiddleware后请求就能正常返回,推测是重载场景下HttpOnly Cookie没有被附加到请求中。目前临时给useFetch加了server: false绕过问题,但这样就失去了SSR能力,希望找到能保留服务器端渲染的解决办法。
相关代码
Nuxt页面代码
<script setup> definePageMeta({ middleware: 'auth' }) const {data:posts} = await useFetch(useRuntimeConfig().public.API_URL+'/api/posts', { credentials: 'include', }) </script>
Express路由代码
PostRoute.get('/', [checkTokenMiddleware], getAllPost)
解决思路与方案
1. 服务器端请求手动传递Cookie
Nuxt的SSR阶段,useFetch是在服务器端发起请求的,此时浏览器的Cookie不会自动同步到服务器端的请求里。需要手动从Nuxt的请求上下文中获取Cookie,再传递给API请求:
<script setup> definePageMeta({ middleware: 'auth' }) const { data: posts } = await useFetch('/api/posts', { credentials: 'include', headers: useRequestHeaders(['cookie']) // 从当前请求头中取出Cookie并传递给API }) </script>
2. 配置Nuxt代理(推荐)
如果API和Nuxt不在同一域名下,配置代理可以避免跨域问题,同时服务器端请求时会自动内部转发,减少Cookie传递的额外问题。在nuxt.config.ts中添加:
export default defineNuxtConfig({ runtimeConfig: { public: { API_URL: process.env.API_URL || 'http://localhost:3001' } }, proxy: { '/api': { target: process.env.API_URL, changeOrigin: true } } })
之后useFetch就可以直接用相对路径调用API,配合上面的Cookie传递逻辑即可:
const {data:posts} = await useFetch('/api/posts', { credentials: 'include', headers: useRequestHeaders(['cookie']) })
3. 检查Express的Cookie设置
确保HttpOnly Cookie配置了正确的属性,避免因为域名、SameSite等规则导致无法传递:
res.cookie('token', token, { httpOnly: true, secure: process.env.NODE_ENV === 'production', // 生产环境启用HTTPS时开启 sameSite: 'lax', // 跨域场景可设为'none'(需配合secure: true) domain: '.yourdomain.com', // 根据实际域名配置,确保覆盖Nuxt和API域名 path: '/' })
4. 验证服务器端是否收到Cookie
可以在checkTokenMiddleware中打印请求头,确认服务器端是否接收到了Cookie,方便排查问题:
const checkTokenMiddleware = (req, res, next) => { console.log('Received Cookie:', req.headers.cookie); // 原有验证逻辑... }
内容的提问来源于stack exchange,提问作者stalwart1014
相关产品推荐
相关产品推荐

