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

OAuth回调调用res.redirect报Cannot set headers错误如何实现重定向

错误根源

你遇到的Cannot set headers after they are sent to the client报错,核心原因是代码逻辑中重复发送了响应:
res.redirect()本身已经向客户端返回了302状态码和跳转地址的响应头,完成了完整的HTTP响应流程,后续执行的res.status(200).send(body2)尝试再次发送响应,触发了Node.js HTTP服务的规则限制,同时也导致redirect无法正常生效。

正确使用redirect的修复方案

直接删除res.redirect后的res.status(200).send(body2)代码即可。如果需要将OAuth接口拿到的资源数据传递给客户端,可选两种实现方式:

  • 数据量小、无敏感信息时,将数据序列化后拼接在跳转URL的query参数中:
if (!error2 && response2.statusCode == 200) {
  const oauthData = encodeURIComponent(body2);
  res.redirect(`http://localhost:3000?oauth_data=${oauthData}`);
  console.log(JSON.parse(body2));
}
  • 有敏感数据或数据量较大时,先将数据存入服务端session/缓存,跳转后由客户端主动调用接口拉取对应数据。

替代跳转方案

如果不使用服务端redirect,可改为返回前端脚本实现主动跳转,还可以直接将数据注入到前端上下文:

if (!error2 && response2.statusCode == 200) {
  res.send(`
  <script>
    // 可直接把OAuth返回的数据挂载到window对象供前端使用
    window.oauthResource = ${body2};
    location.href = 'http://localhost:3000';
  </script>
  `);
  console.log(JSON.parse(body2));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:27:03