Node.js Lambda发送POST请求无法保存HttpOnly Cookie问题求助
问题根源
跨域POST请求下浏览器不保存HttpOnly Cookie,核心是两个配置缺失:
- 前端
fetch请求默认不会处理跨域Cookie,需显式开启凭证支持 - 后端CORS响应头未声明允许携带凭证,浏览器会拦截Set-Cookie
修复步骤
1. 修改前端fetch请求
在请求配置中添加credentials: 'include',允许跨域请求携带和保存Cookie:
const response = await fetch("https://api adres/login", { method: "POST", headers: { "Content-Type": "application/json", 'x-api-key': 'AVlZ2gnoY99k9la40l5Ph1Mt5AdzLtqE4w5qLl48' }, credentials: 'include', // 关键:开启跨域凭证支持 body: JSON.stringify({username,password,rememberme}), });
2. 完善后端Lambda响应头
新增Access-Control-Allow-Credentials: true头,同时确保Access-Control-Allow-Origin是明确的前端域名(不能用*,否则凭证配置无效):
return { statusCode: 200, headers: { 'Access-Control-Allow-Origin': 'https://front-end domain', // 必须是具体前端域名,禁止通配符 'Access-Control-Allow-Credentials': 'true', // 允许跨域携带凭证 'Content-Type': 'application/json', 'Set-Cookie': `token=${token}; path=/; HttpOnly; Domain=apidomain; SameSite=Strict; secure; expires=Tue, 06 Sep 2023 22:10:32 GMT` }, body: JSON.stringify(body) }
额外注意事项
Domain字段需匹配API的实际域名,若要让前端主域共享Cookie,可设为.your-main-domain.com(比如API是api.your-main-domain.com,前端是www.your-main-domain.com)Secure字段要求请求必须是HTTPS,当前配置符合要求,若在本地测试需去掉(但生产环境必须保留)- 可通过浏览器开发者工具验证:Network面板查看POST请求的响应头是否包含正确的Set-Cookie和Access-Control-Allow-Credentials,再到Application面板的Cookies列表确认Cookie是否已保存
内容的提问来源于stack exchange,提问作者chieffker
相关产品推荐
相关产品推荐

