使用NestJS(Fastify)为NextJS前端设置Cookie失败问题及解决
环境信息
- API服务:基于NestJS(Fastify)搭建,地址
localhost:3001 - 前端服务:基于NextJS 14.0.3搭建,地址
localhost:3000
问题现象
尝试通过响应头Set-Cookie设置Cookie时失败:
- 响应头中的
Set-Cookie格式看似正确,但Chrome开发者工具的Application/Cookie标签中无法找到对应的Cookie,且控制台无任何报错或警告 - 在Insomnia API客户端中测试时,Cookie可正常生效
响应头信息
HTTP/1.1 201 Created vary: Origin access-control-allow-origin: http://localhost:3000 access-control-allow-credentials: true content-type: application/json; charset=utf-8 set-cookie: token=ced93884671e13aa95e9368f; Path=/; Expires=Sat, 26 Nov 2033 13:10:59 GMT; HttpOnly content-length: 203 Date: Wed, 29 Nov 2023 13:10:59 GMT Connection: keep-alive Keep-Alive: timeout=72
请求头信息
Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Cache-Control: no-cache Connection: keep-alive Content-Length: 49 Content-Type: application/json Host: localhost:3001 Origin: http://localhost:3000 Pragma: no-cache Referer: http://localhost:3000/ Sec-Ch-Ua: "Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24" Sec-Ch-Ua-Mobile: ?0 Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-site User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36
解决方法
问题根源在于前端axios请求配置中缺失withCredentials属性,该属性用于允许跨域请求携带Cookie。只需在axios请求中开启此配置即可:
单请求配置
axios.post('http://localhost:3001/api/your-endpoint', requestData, { withCredentials: true })
全局配置
// 在axios初始化时设置全局默认值 axios.defaults.withCredentials = true
内容的提问来源于stack exchange,提问作者Ivan Uno
相关产品推荐
相关产品推荐

