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

Node.js登录请求无响应求助:无法渲染secrets页面

登录请求无响应的问题修复

你的代码存在多个未处理的分支,导致HTTP请求始终无法得到服务器响应,浏览器会一直处于等待状态,最终表现为页面长时间无响应。具体问题和修复方案如下:

  • 错误处理缺失:当User.findOne查询抛出错误时,你仅打印了错误信息但未给客户端返回任何响应,请求会一直挂起。需补充错误状态码及提示。
  • 未找到用户的场景未处理:如果查询不到匹配的用户(foundUser为null),没有对应的响应逻辑,请求会持续等待。
  • 密码不匹配的场景未处理:密码验证失败时,同样没有返回任何响应,导致请求无法正常结束。

修复后的完整代码:

app.get("/login", (req, res) => {
  res.render("login");
});

app.post("/login", function (req, res) {
  const username = req.body.email;
  const password = req.body.Password;

  User.findOne({ email: username }, (err, foundUser) => {
    if (err) {
      console.log(err);
      res.status(500).send('服务器内部错误'); // 错误分支添加响应
    } else {
      if (foundUser) {
        if (foundUser.password === password) {
          res.render("secrets");
        } else {
          res.send('密码错误'); // 密码不匹配时返回响应
        }
      } else {
        res.send('用户不存在'); // 未找到用户时返回响应
      }
    }
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:25:27