You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Node.js实现JWT认证时前端Cookie为null但Postman正常如何解决

问题原因

这是跨域请求下的Cookie传输限制导致的问题:你的前后端运行在不同端口(React前端默认3000端口,后端为3855端口)属于跨域场景,浏览器遵循同源策略默认不会在跨域请求中携带Cookie,也不会接受跨域响应返回的Set-Cookie头,而Postman不受跨域规则限制,所以测试正常。

修复方案

1. 后端CORS配置修改

你当前的CORS配置是默认放开所有来源,但没有开启凭证支持,修改server.js中的cors配置:

// 替换原有app.use(cors())
app.use(cors({
  origin: "http://localhost:3000", // 替换为你实际前端的访问地址,端口要完全匹配
  credentials: true // 允许跨域请求携带凭证(Cookie)
}))

2. 后端Cookie设置优化

登录接口中设置Cookie时补充SameSite属性,适配浏览器最新的Cookie安全策略:

// 替换原有res.cookie代码
res.cookie('token', token, {
  httpOnly: true,
  sameSite: 'Lax', // 本地开发用Lax即可,生产环境如果前后端域名不同需要设为None,同时开启secure: true(必须搭配HTTPS使用)
  // secure: process.env.NODE_ENV === 'production'
})

3. 前端Axios请求配置

所有和后端交互的请求都需要开启withCredentials,允许Axios携带和存储跨域Cookie:

全局配置(推荐,一次配置所有请求生效)

在前端项目的入口文件(比如index.js)中添加:

import axios from 'axios'
axios.defaults.withCredentials = true

单独请求配置(如果不想全局改)

修改登录请求:

axios.post("http://localhost:3855/students/login", options, {
  withCredentials: true
}).then(// 原有逻辑

修改校验token请求:

axios.get("http://localhost:3855/students/verifyToken", {
  withCredentials: true
}).then(// 原有逻辑

额外问题修复

你checkToken接口存在代码笔误,会导致接口报错:

// 原有错误写法
return res.json(400).json({"message":"token verification failed"})
// 修改为
return res.status(400).json({"message":"token verification failed"})

内容的提问来源于stack exchange,提问作者Mohammad Fahad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:24:03