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

如何修复Express中的Error [ERR_HTTP_HEADERS_SENT]错误?

解决Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client错误

问题出在这行代码:

return res.sendStatus(200).json(table).end();

sendStatus(200)会直接发送一个包含200状态码的完整响应(包括响应头和空响应体),之后再调用.json(table)和.end(),相当于试图再次修改响应头、发送新的响应内容,这就触发了重复发送响应的错误。

你有两种修正方式:

  • 如果需要返回创建好的table数据,把这行改成:
    return res.status(200).json(table);
    
    status(200)仅设置响应状态码,不会发送响应,.json(table)会把数据作为响应体发送,并且自动完成响应结束(不需要额外调用.end())。
  • 如果不需要返回table数据,直接保留:
    return res.sendStatus(200);
    

修正后的完整代码:

export const build_tab = async (req : express.Request , res : express.Response ) => {
try{
const { seats, number } = req.body ;

    if(!seats||!number){
       return res.sendStatus(400);
    }
    const _id = require('uuid').v4() ;
   
    const table = await createTable({
        _id,
        number,
        seats
    });

    // 修正后的响应写法
    return res.status(200).json(table);
}
catch(error){
   console.log(error)         ;
   return res.sendStatus(400) ;
}
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 21:12:48