Node.js+React JWT认证:POST请求无法获取Cookie问题
我在Node.js后端+React前端实现JWT认证,登录时后端返回accessToken并设置了带refreshToken的Cookie。测试发现GET接口能正常获取到Cookie,但POST接口后端打印[Object: null prototype] {},拿不到Cookie。
相关代码
后端设置Cookie的代码
res.cookie('jwt', refreshToken, { httpOnly: true, secure: true, sameSite: 'None', maxAge: 24 * 60 * 60 * 1000 })
GET请求前端代码(正常工作)
const testCookiesGetMethod = (e) => { e.preventDefault(); axios.get('auth/test',{ withCredentials: true, headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }); }
GET后端代码及输出
export const testGet = (req, res) => { console.log(req.cookies); }
输出:
{ jwt: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InllbGxvdyIsImlhdCI6MTY2OTM1NjYxMiwiZXhwIjoxNjY5NDQzMDEyfQ.5cibdr1bboyNf3p4fUXkp4nVO3SE2lPi_h5FUBrzqjE' }
POST请求前端代码(无法携带Cookie)
const testCookiesPostMethod = (e) => { e.preventDefault(); axios.post('auth/test',{ withCredentials: true, headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }); }
POST后端代码及输出
export const testPost = (req, res) => { console.log(req.cookies); }
输出:
[Object: null prototype] {}
解决办法
1. 修正Axios POST请求的参数位置
Axios的post方法签名是axios.post(url[, data[, config]]),你把配置项(withCredentials、headers)放到了请求体参数的位置,导致withCredentials: true没有生效,浏览器不会携带Cookie发送请求。
修正后的POST前端代码:
const testCookiesPostMethod = (e) => { e.preventDefault(); // 空请求体(如果不需要传数据),配置项放到第三个参数 axios.post('auth/test', {}, { withCredentials: true, headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }); }
2. 确保后端正确处理跨域预检请求
因为你设置了sameSite: None,跨域场景下浏览器会先发送OPTIONS预检请求,后端必须正确响应这个请求,允许携带凭证(Credentials),否则后续POST请求的Cookie不会被发送。
如果用cors中间件,配置如下:
const cors = require('cors'); app.use(cors({ origin: 'https://your-frontend-domain.com', // 必须指定具体域名,不能用*(带Credentials不允许*) credentials: true, // 允许携带Cookie allowedHeaders: ['Content-Type', 'Accept'], methods: ['GET', 'POST', 'OPTIONS'] // 允许预检请求 }));
3. 确认secure: true的生效条件
当设置sameSite: None时,必须搭配secure: true,这要求网站必须是HTTPS协议。本地开发用localhost时,浏览器会豁免这个限制,可以正常测试;如果是HTTP环境,secure: true的Cookie不会被设置,自然也无法携带。
内容的提问来源于stack exchange,提问作者golden goal
相关产品推荐
相关产品推荐

