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

React对接Nest本地开发:Session Cookie未在浏览器存储问题

跨域会话Cookie不存储/不携带问题解决方案

前端代码修改

跨域请求时,浏览器默认不会处理Cookie,必须在fetch中添加credentials: 'include'选项,才能让浏览器保存响应的Cookie,并且在后续请求中自动携带:

const response = await fetch('http://localhost:3000/admins/auth/login', {
  method: 'POST',
  headers: { 
    'Content-Type': 'application/json',
  },
  credentials: 'include', // 必须添加,开启跨域凭证支持
  body: JSON.stringify({ email, password }),
});

后续调用/isLogged等需要验证会话的接口时,同样要加上该选项。

后端配置调整

1. 配置CORS允许凭证

跨域场景下,后端必须明确指定允许的前端Origin(不能用*),同时开启凭证支持。如果使用Fastify,需安装@fastify/cors并做如下配置:

fastify.register(require('@fastify/cors'), {
  origin: 'http://localhost:3200', // 前端的地址
  credentials: true, // 允许携带凭证
});

2. Cookie参数优化

开发环境下,跨域场景的sameSite配置需要调整:

cookie: {
  path: '/',
  httpOnly: true,
  maxAge: +process.env.SESSION_MAX_AGE,
  sameSite: process.env.NODE_ENV === "production" ? 'none' : 'none',
  secure: process.env.NODE_ENV === "production" ? true : false,
}

注意:Chrome浏览器默认会拦截HTTP协议下的SameSite=None Cookie,需要在chrome://flags/中开启Insecure origins treated as secure,并添加http://localhost:3000和http://localhost:3200两个地址。

更稳妥的开发方案

如果不想修改浏览器设置,可以给前端配置代理,将请求转发到后端,避免跨域问题。比如用Vite的代理配置:

// vite.config.js
export default {
  server: {
    proxy: {
      '/admins': {
        target: 'http://localhost:3000',
        changeOrigin: true,
      },
    },
  },
};

之后前端只需请求/admins/auth/login即可,浏览器会认为是同域请求,Cookie能正常存储和携带。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 10:02:15