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

Node.js使用Mongoose查询数据时HTTP返回200但无响应内容

问题分析与修复方案

你的代码存在两个关键问题,导致Postman能收到200状态码但拿不到响应数据:

1. 路由处理函数未向客户端返回响应

_getallUsersByAccount函数里成功获取到data后,没有通过res对象将数据发送给客户端,浏览器/Postman只能收到默认的200状态码,却没有实际内容。

2. getAccountDetails的错误处理逻辑错误

这个函数不是Express中间件,没有接收next参数,直接调用next(error)会触发未定义错误,且错误无法被上层的try/catch捕获处理。

修改后的完整代码

async function getAccountDetails(authAccount) {
  try {
    const accId = authAccount._id;
    // findById可直接传入ID值,无需包裹成对象
    const account = await Users.findById(accId);
    console.log(account);
    return account;
  } catch (error) {
    // 抛出错误,让上层路由的try/catch捕获处理
    throw error;
  }
}

router.get(
  "/list",
  authMiddleware,
  async function _getallUsersByAccount(req, res, next) {
    try {
      const data = await getAccountDetails(req.authAccount);
      console.log(data);
      // 显式向客户端返回数据
      res.status(200).json(data);
    } catch (error) {
      console.log("获取数据失败:", error);
      next(error);
    }
  }
);

额外优化说明

  • Users.findById({ _id: accId })可以简化为Users.findById(accId),Mongoose的findById方法支持直接传入ID值作为参数,写法更简洁。
  • 错误日志中添加具体错误信息,方便后续排查问题。

内容的提问来源于stack exchange,提问作者Mohamed Amine Hachemi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 18:42:06