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

在Next.js应用中发起Fetch请求时,Express返回的connect.sid Cookie未设置

问题分析与解决方案

你的核心问题是跨域请求时connect.sid Cookie无法被前端正确携带,根源在于CORS配置错误、Session Cookie参数配置不规范,以及Fetch请求的小细节问题,以下是针对性的修复步骤:


1. 修正CORS配置:禁用origin: '*'

当credentials: true时,浏览器不允许CORS的origin设为通配符*,必须指定具体的前端域名(开发/生产环境分别对应),否则浏览器会直接拒绝携带凭证。

修改后的CORS代码:

app.use(
  cors({
    credentials: true,
    origin: 'http://localhost:3000' // 替换为你的前端实际域名,生产环境换成线上地址
  })
);

2. 规范Session Cookie配置

你的Session配置存在参数层级错误,sameSite、secure等Cookie属性必须放到cookie对象内部,且sameSite: 'none'必须配合secure: true(HTTPS环境下),否则浏览器会忽略该Cookie。

修改后的Session代码:

app.use(
  session({
    secret: process.env.EXPRESS_SESSION_SECRET,
    resave: false,
    proxy: true,
    saveUninitialized: false,
    store: sessionStore,
    cookie: {
      maxAge: 1000 * 60 * 60 * 24,
      sameSite: 'none',
      secure: process.env.NODE_ENV === 'production', // 生产环境强制HTTPS,开发环境可设为false
      httpOnly: true, // 明确开启httpOnly,避免前端JS篡改Cookie
    }
  })
);

3. 修正Fetch请求的两个细节

  • 移除冗余的withCredentials: true:这是XMLHttpRequest的属性,Fetch API只需要credentials: 'include'
  • 确保请求URL是完整路径(带http/https):相对路径会导致请求发送到前端域名而非后端,引发跨域问题

修改后的Fetch代码:

fetch(`https://api.invoice-app.naughty-cat.com/invoices/all`, {
  credentials: 'include'
})
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.log(err));

额外检查项

  1. 浏览器隐私设置:如果浏览器开启了「阻止第三方Cookie」,sameSite: 'none'的Cookie会被拦截,开发环境可暂时关闭该限制(Chrome:设置→隐私和安全→第三方Cookie→允许所有Cookie)
  2. OAuth回调响应:确保Github OAuth回调接口返回的响应头中包含正确的Set-Cookie字段,可在浏览器网络面板中查看
  3. Next.js代理配置(可选):如果不想直接请求后端域名,可在next.config.js中配置代理转发,避免跨域问题:
module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'https://api.invoice-app.naughty-cat.com/:path*'
      }
    ]
  }
}

此时Fetch请求可写为fetch('/api/invoices/all', { credentials: 'include' })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:12:52