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

部署至Vercel后Express应用Cookie无法发送与设置问题求助

修复Vercel部署Express后Cookie无法设置的问题

针对跨域Cookie在Vercel部署后失效的问题,以下是具体修复步骤:

一、后端Express代码修复

1. 修正CORS Origin配置

移除origin末尾的斜杠,避免origin匹配失败:

app.use(cors({
  origin: 'https://tester-virid-seven.vercel.app',
  credentials: true
}));

2. 补充Cookie的SameSite属性

跨域场景下必须设置sameSite: 'none',且与secure: true配合(Vercel默认是HTTPS环境):

app.get('/', (req, res) => {
  res.status(200).cookie("AUTH", "example", {
    maxAge: 900000,
    httpOnly: false,
    secure: true,
    sameSite: 'none',
    expires: new Date(Date.now() + 1000*60)
  }).json({cookie: req.cookies.AUTH});
});

3. 适配Vercel Serverless部署

Vercel不支持app.listen(),需导出Express实例作为Serverless函数:

// 移除原有的app.listen(3000, ...)代码
module.exports = app;

同时在项目根目录创建vercel.json配置文件,指定函数入口与路由规则:

{
  "functions": {
    "api/index.js": {
      "runtime": "@vercel/node@20"
    }
  },
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/api/index.js"
    }
  ]
}

(注意:将Express代码移至api/index.js目录下,Vercel会自动识别该目录为Serverless函数入口)

二、前端代码修复

调整Cookie读取时机,确保在请求完成后再获取Cookie:

<script>
  axios.defaults.withCredentials = true
  axios.get('https://cookie-test-theta.vercel.app/')
  .then(res => {
    console.info(res);
    alert(document.cookie);
  })
  .catch(err => console.error(err));
</script>

额外注意事项

  • 确保前后端均处于HTTPS环境(Vercel默认提供HTTPS,无需额外配置)
  • 本地测试时可将secure设为false,生产环境必须保持true
  • 确认浏览器未禁用第三方Cookie(部分浏览器默认限制,测试时可临时开启)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 03:44:58