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

ExpressJS仅发送一次响应头却报多次设置头错误如何解决

错误根因

你触发报错的核心原因是混用了Express的响应方法:
res.sendStatus(状态码)本身是完整响应方法,调用后会直接发送响应结束当前请求,等价于res.status(状态码).send(对应状态文本)的简写。你在sendStatus之后又链式调用了.json()/.send(),等于试图在响应已经发送完成后再次设置响应头、返回内容,因此触发了Cannot set headers after they are sent to the client错误。

修复方案

把sendStatus替换为仅设置状态码、不会主动发送响应的status方法即可,调整后代码如下:

router.put("/:_id", async (req: Request, res: Response) => {
  try {
    const artist: IArtist = req.body;
    // 可选优化:添加new: true参数,返回更新后的文档(默认返回更新前的旧数据)
    const updatedArtist = await Artist.findOneAndUpdate(
      { _id: req.params._id }, 
      artist, 
      { new: true }
    );
    return res.status(200).json(updatedArtist);
  } catch (err) {
    return res.status(400).send("Couldn't update artist");
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:42:02