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

登录接口!found条件失效致浏览器持续加载问题求助

问题分析

当输入不存在的邮箱时,DB_Collection.findOne()返回null,此时执行found.password会直接抛出TypeError: Cannot read properties of null (reading 'password'),错误被catch块捕获,但你的catch里只是return err,没有给客户端返回任何响应,导致浏览器一直处于等待状态,不会显示错误提示。

修复方案
  1. 先检查found是否存在,只有当用户存在时,再执行密码比对
  2. 在catch块中添加响应逻辑,确保任何错误都能返回给客户端

修改后的代码:

Router.post('/', async(req, res) => {
    try {
        const loginData = {
            email : req.body.email,
            password : req.body.password
        }

        const found = await DB_Collection.findOne({email : loginData.email})

        // 先判断用户是否存在
        if (!found) {
            return res.send("Incorrect email or password..!");
        }

        // 仅当用户存在时,再比对密码
        const passwordOK = await bcrypt.compare(loginData.password, found.password)

        if (!passwordOK) {
            res.send("Incorrect email or password..!");
        } else {
            res.send("Logged in successfully...!");
        }
    } catch(err) {
        // 捕获所有异常,返回错误响应
        console.error(err);
        res.status(500).send("Server error occurred");
    }
})
关键说明
  • 提前判断!found并返回响应,避免后续访问found.password抛出错误
  • catch块中必须调用res相关方法(比如res.send、res.status),否则客户端会一直等待,出现持续加载的情况
  • 统一错误提示内容,避免泄露用户是否存在的信息,提升安全性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:06:47