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

Express服务无法在React前端浏览器中设置Cookie求助

问题描述

提前致歉,此问题可能重复。我试过各种Stack Overflow和其他方案,还是没解决。我想通过Express服务器给React前端发送并设置Cookie,用于后续请求的身份认证。这个功能在Insomnia和9090主机上正常运行,但部署到正式服务器后完全无法设置Cookie,请求头均正常显示,控制台也无报错信息。

React请求代码
export const logIn = (formInput) => {
  return listApi.post(`/users/authenticate`, formInput, {withCredentials:true})
  .then( ({ data }) => {
    return data
  })
}
Express相关代码

CORS配置

app.use(cors({
  origin: "http://192.xxx.x.xx:xxxx",
  credentials: true,
  origin: true
}));

响应设置代码

res.status(200)
  .header('Access-Control-Allow-Credentials', true)
  .header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
  .header("Access-Control-Allow-Origin", "http://192.168.1.69:3000")
  .header("Access-Control-Allow-Methods", "GET,POST,PATCH,PUT,DELETE,OPTIONS")
  .cookie('access_token', token, {expires:tokenExpire, 
    sameSite: 'None', 
    secure: true, 
    httpOnly: true, 
    Domain: 'http://192.168.1.69:3000'})
  .send({ msg: 'success' });
} else {
  Promise.reject( {status: 401, msg: 'unauthorized - invalid username and password'})
  .catch(err => next(err))
}
};
排查与解决方案建议
  • 修复CORS配置冲突:当前CORS配置重复定义了origin字段,需删除重复项,统一设置为前端实际访问的域名/IP(如http://192.168.1.69:3000),避免同时设置具体值和true。
  • 修正Cookie的Domain参数:Domain不能包含协议(http://)和端口号,应改为纯IP或域名,比如192.168.1.69,浏览器会拒绝带协议/端口的Domain设置。
  • 调整Secure参数:如果正式服务器使用HTTP而非HTTPS,secure: true会导致浏览器不保存Cookie,需将其改为false;若为HTTPS环境则保留。
  • 校验SameSite参数:当设置SameSite: None时必须配合secure: true,但HTTP环境下两者不能共存,可尝试改为SameSite: Lax(适配多数跨域场景)。
  • 移除重复的CORS响应头:已通过cors中间件配置CORS,无需手动设置Access-Control-*系列响应头,避免冲突。
  • 确认正式服务器域名匹配:确保cors中间件的origin与前端实际访问的域名(含端口)完全一致,若使用反向代理,需确认代理后的域名是否匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:10:28