无法在不出错的情况下发回 res.send

Can't send res.send back without getting errors

我一定是遗漏了一些重要的东西

router.get("/", async (req, res, next) => {
  let posts = await loadPostsCollection();
  console.log(await posts.find({}).toArray());
  res.send(await posts.find().toArray());
});

async function loadPostsCollection() {
  const client = await mongodb.MongoClient.connect(uri, {
    // useNewUrlParser: true,
    useUnifiedTopology: true,
  });
  return client.db("stack_1").collection("posts");
}

为什么我收到 headers 已发送错误?

Express js @latest MongoDb Atlas 免费集群 'posts' collection 中包含单个项目的数据库 我一定错过了一些非常简单的东西。

控制台日志按预期工作... 我很确定我所有的异步等待调用都在正确的位置...

求助..?

编辑:错误:

http://localhost:3000/api/posts: 2020-07-23T23:57:06+03:00
[ { _id: 5f19e338adcae71eca1c3658, name: 'liad', status: 'active' } ]
(node:7894) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:536:11)
    at ServerResponse.header (/media/liad/Data/liad_dev/vue-express-mongo/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/media/liad/Data/liad_dev/vue-express-mongo/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/media/liad/Data/liad_dev/vue-express-mongo/node_modules/express/lib/response.js:267:15)
    at ServerResponse.send (/media/liad/Data/liad_dev/vue-express-mongo/node_modules/express/lib/response.js:158:21)
    at /media/liad/Data/liad_dev/vue-express-mongo/server/routes/api/posts.js:10:7
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:7894) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:7894) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

编辑 2:

重构一切以使用 mongoose

我遇到同样的错误!

  const post = new Post({
    title: req.body.title,
    desc: req.body.desc,
  });
  console.log(post);
  post
    .save()
    .then((response) => {
      res.json(response);
    })
    .catch((err) => {
      res.json({ message: err });
    });
});

在 posts.find 的第二次出现中,没有空对象作为参数。这可能是个问题吗? 此外,将异步函数的函数体放在 try/catch 块中会更安全,因为现在不会捕获异常。

我找到了解决办法。

我定义我的应用程序的方式是尝试动态访问我的路由器,而不必一个接一个地定义它们

let routerPath = "/api/members";
app.use((req, res, next) => {
  let routerPath = req.path;
  app.use(`${routerPath}`, require(`./routes${routerPath}`));
  next();
});

我的错误是因为我有一个额外的 next();

let routerPath = "/api/members";
app.use((req, res, next) => {
  let routerPath = req.path;
  next();
  app.use(`${routerPath}`, require(`./routes${routerPath}`));
  next();
});

出于某种原因破坏了我的应用程序...

感谢大家的努力