Express后端req.cookies获取空对象,Gatsby跨域Cookie问题求助
核心问题分析
- 后端Cookie参数错误:Express的
res.cookie方法不存在expiresIn选项,导致Cookie未正确配置过期规则,可能被浏览器自动丢弃。 - SSR请求未传递Cookie:Gatsby的
getServerData在服务器端执行,发起的fetch不会自动携带浏览器请求Gatsby页面时的Cookie,需手动传递。
修复步骤
1. 修正后端Cookie设置代码
将res.cookie中的expiresIn替换为Express支持的maxAge或expires选项:
// 后端index.js POST接口修改 app.post('/hello', (req, res)=> { const {text} = req.body res.cookie('the_cookie', 'NOMNOMNOM', { path: '/', httpOnly: true, sameSite: 'lax', maxAge: 1000 * 3600 // 单位为毫秒,设置1小时有效期 // 也可以使用:expires: new Date(Date.now() + 1000 * 3600) }) res.status(200).json({message: text}) })
2. SSR请求手动传递Cookie
修改ssr.js中的getServerData,从Gatsby的请求对象中提取Cookie并添加到fetch请求头:
export async function getServerData({ req }) { // 解构获取Gatsby的请求对象 try { const res = await fetch(`http://localhost:3001/hi`, { method: "GET", mode: 'cors', credentials: 'include', headers: { "Accept": "application/json", "Content-Type": "application/json", "Cookie": req.headers.cookie || '' // 手动传递浏览器携带的Cookie }}) if (!res.ok) { throw new Error(`Response failed`) } return { props: await res.json(), } } catch (error) { return { status: 500, headers: {}, props: {} } } }
3. 前端请求验证
前端sendRequest函数已正确设置credentials: 'include',确保浏览器发送POST请求时会携带Cookie,无需额外修改。
验证流程
- 重启Express后端与Gatsby前端服务。
- 点击前端按钮触发POST请求,通过浏览器开发者工具的「Application→Cookies」确认
the_cookie已被成功设置。 - 访问SSR页面,查看后端控制台输出,
req.cookies应显示{ the_cookie: 'NOMNOMNOM' }。
内容的提问来源于stack exchange,提问作者LeiCorre
相关产品推荐
相关产品推荐

