Javascript 类型错误:next 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42886931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:29:51  来源:igfitidea点击:

TypeError: next is not a function

javascriptnode.jsmongodbexpressmongoose

提问by SudokuNinja

I'm running a Node.js-server and trying to test this Rest API that I made with Express. It's linked up to MongoDB using Mongoose.

我正在运行 Node.js-server 并尝试测试我用 Express 制作的这个 Rest API。它使用 Mongoose 连接到 MongoDB。

I'm testing the individual routes using Postman and I get an error when trying to send a PUT-request to this route:

我正在使用 Postman 测试各个路由,但在尝试向该路由发送 PUT 请求时出现错误:

// PUT /meetings/:id
// Route for editing a specific meeting
router.put("/:id", function(req, res, next) {
    req.meeting.update(req.date, function(err, result) {
      if(err) return next(err);
      res.json(result);
    });
});

The error retrieved is this:

检索到的错误是这样的:

events.js:141
      throw er; // Unhandled 'error' event
      ^

TypeError: next is not a function

I cannot figure out where exactly this is coming from. I'm using the router.params-method to specify how the :id-parameter should be handled like this:

我无法弄清楚这究竟是从哪里来的。我正在使用 router.params-method 来指定 :id-parameter 应该如何处理,如下所示:

router.param("id", function(req, res, id, next) {
  Meeting.findById(id, function(err, meeting) {
    if (err) return next(err);
    if (!meeting) {
      err = new Error("Meeting not found");
      err.status = 404;
      return next(err);
    }
    req.meeting = meeting;
    return next();
  });
});

回答by Jamie

Not an answer but just wanted to say that it's so easy to find error like these if you use Promises instead of nested callbacks. An example of above code refactorized.

不是答案,只是想说如果您使用 Promise 而不是嵌套回调,很容易找到这样的错误。上面代码重构的一个例子。

router.param("id", (req, res, id) => {
  Meeting.findById(id)
    .then(meeting => { meeting })
    .catch(err => res.status(404).send("Meeting not found"))
});

回答by SudokuNinja

So I figured it out. It was a much smaller error than I thought. I had the parameters to the callback-function in my router.param-method in the wrong sequence. The next-keyword should be where id was. This code fixed the problem:

所以我想通了。这是一个比我想象的要小得多的错误。我的 router.param-method 中的回调函数的参数顺序错误。next-keyword 应该是 id 所在的位置。这段代码解决了这个问题:

router.param("id", function(req, res, next, id) {
  Meeting.findById(id, function(err, meeting) {
    if (err) return next(err);
    if (!meeting) {
      err = new Error("Meeting not found");
      err.status = 404;
      return next(err);
    }
    req.meeting = meeting;
    return next();
  });
});