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

无法在客户端获取Set-Cookie Header及重复请求问题解决

解决方案

一、解决重复请求问题

1. 防止按钮重复点击触发多次请求

如果是用户快速点击按钮导致重复提交,给按钮添加点击后禁用逻辑:

btn.addEventListener('click', async () => {
  // 点击后立即禁用按钮,阻止重复提交
  btn.disabled = true;
  const pass = document.querySelector('#password')
  const email = document.querySelector('#email')
  
  try {
    const response = await axios.post('http://localhost:4550/api/v1/auth/login', {
      email: email.value,
      password: pass.value,
    });
    console.log(response.headers['set-cookie']);
  } catch (err) {
    console.log(err);
  } finally {
    // 请求完成后恢复按钮可点击状态
    btn.disabled = false;
  }
})

2. 区分跨域OPTIONS预检请求(正常行为)

如果204是浏览器自动发送的OPTIONS预检请求(跨域场景下的标准流程),这属于正常行为无需停止,但要确保服务端正确配置CORS,允许后续POST请求携带Cookie。

二、解决无法获取Set-Cookie的问题

1. 客户端开启axios凭证携带

跨域请求时,axios默认不会携带Cookie,也无法读取Set-Cookie,需开启withCredentials:

axios.post('http://localhost:4550/api/v1/auth/login', {
  email: email.value,
  password: pass.value,
}, {
  withCredentials: true // 关键配置,允许携带凭证
}).then((response) => {
  console.log(response.headers['set-cookie'])
}).catch((err) => console.log(err))

2. 修复服务端Cookie的secure参数

你的secure属性传了字符串'production',但该参数要求布尔值,正确做法是根据环境动态设置:

const oneDay = 1000 * 60 * 60 * 24
res.cookie('token', token, {
  httpOnly: true,
  expires: new Date(Date.now() + oneDay),
  secure: process.env.NODE_ENV === 'production', // 开发环境为false,生产环境为true
  signed: true,
})

开发环境(http://localhost)下secure: true会导致浏览器拒绝存储Cookie,因为非HTTPS环境不满足secure要求。

3. 服务端配置CORS允许凭证

确保Express服务端的CORS配置允许携带凭证,并指定合法的前端源:

const cors = require('cors');
app.use(cors({
  origin: 'http://localhost:你的前端端口', // 替换为实际前端地址
  credentials: true, // 允许携带Cookie等凭证
  optionsSuccessStatus: 204 // 匹配OPTIONS请求的204响应
}));

不设置credentials: true的话,即使客户端开启withCredentials,浏览器也不会传递Cookie,也不会暴露Set-Cookie给JS。

三、验证步骤

  1. 打开浏览器Network面板,确认POST请求的响应头中存在Set-Cookie;
  2. 检查axios请求是否开启withCredentials;
  3. 确认服务端CORS配置正确,且Cookie的secure参数符合当前环境;
  4. 测试按钮点击逻辑,确认不会触发重复请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:37:30