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

Mongoose findOne返回undefined触发ERR_HTTP_HEADERS_SENT报错如何解决

代码问题排查与修复

错误原因

1. ERR_HTTP_HEADERS_SENT报错原因

你在if (!user)分支调用res.send()返回响应后,没有终止后续代码执行,程序会继续向下执行cryptr.decrypt(user.password)逻辑:当用户不存在时user为null,访问user.password会抛出异常,被catch块捕获后再次调用res.status(500).send(),同一个请求尝试返回两次响应,就触发了该报错。

2. 始终返回「User Not Found」的原因

存在两种可能:

  • 服务端没有配置请求体解析中间件,导致Postman传递的参数没有被正确解析,req.body.email为undefined,查询用户始终匹配不到结果
  • 即使用户存在,后续解密、密码校验逻辑抛出异常时,if (!user)分支的响应已经发送给前端,你看到的就是先返回的「User Not Found」提示

修复方案

首先在所有res.send()调用前加return,终止当前分支的后续代码执行,避免重复返回响应:

exports.loginUser = async (req, res) => {
    try{
      const user = await userTable.findOne({ email:req.body.email });
      if (!user){
        return res.send({
          status: 404,
          message: "User Not Found"
        });
      }

      const hashpass = cryptr.decrypt(user.password);
      if (hashpass == req.body.password){
        const accessToken = jwt.sign({ id: user._id, email: user.email }, process.env.JWT_PASS, {expiresIn:"1d"});
        return res.send({
          status: 200,
          data: user,
          jwt: accessToken
        });
      }else{
        return res.send({
          status: 404,
          message: "Wrong password"
        });
      }
    }catch(err){
      return res.status(500).send({
        status: 0,
        message: "catch issue" + err.message
      });
    };
};

修复后如果还提示「User Not Found」,再按以下步骤排查:

  • 确认express服务已配置JSON解析中间件:app.use(express.json()),如果用x-www-form-urlencoded格式传参还需要加app.use(express.urlencoded({ extended: true }))
  • 在findOne前打印req.body,确认Postman传递的参数已经被正常解析

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:15:05