【问题标题】:Express - next() is not calling in controllerExpress - next() 没有在控制器中调用
【发布时间】:2019-07-03 12:46:36
【问题描述】:

在我的 MEAN 堆栈应用程序中,我有 2 个集合 - 新闻和评论。发表评论时,将首先保存,然后更新新闻收藏。

我在 express 的帮助下使用了 2 个函数,如下所示:

//CommentsController.js
//Function  1
exports.addComment = (req, res, next) => {
  const comment = new Comment({
    //Key values
  });
  comment
    .save()
    .then(createdComment => {
      req.createdComment = comment;
      next();
    })
};


//Function 2
exports.updateNews = (req, res, next) => {
  let newsId = req.body.newsId;
  let comment = req.createdComment;
  News.findById(newsId)
    .then(news => {
      News.update({ _id: newsId }, {
        $push: { comment }
      })
      .then(item => {
        res.status(201).json({
          message: "Comment added successfully"
        });
      })
    });
}

我的路由器文件如下:

const express = require("express");
var CommentsController = require('../controllers/commentsController');

const router = express.Router();
router.post("", CommentsController.addComment);
module.exports = router;

我面临的问题是,成功保存 addComment 后,即使调用 next(),它也不会调用“updateNews”函数。我不确定缺少什么。

【问题讨论】:

  • 为什么会这样?是什么将这两个功能联系在一起?似乎您没有包括人们能够提供帮助所需的一切。
  • @DaveNewton,有了 Express,我们就不必连接它们了。 next() 就足够了
  • 它怎么知道接下来会发生什么? (而且我会从证据中争辩说“next()”是足够的,因为它不起作用。)
  • 发布你的路由器/中间件
  • 你注册updateNews作为路由器中的下一个中间件了吗?

标签: express mean-stack mean


【解决方案1】:

正如@vapurrmaid 提到的(在 cmets 中),我找到了自己问题的答案。

答案是:

router.post("", CommentsController.addComment, CommentsController.updateNews);


谢谢@vapurrmaid

【讨论】:

  • addCommentToNews 根据你的问题应该是addComment
  • ... 大致如我所说,包括另一条评论说你没有提供足够的信息来提供帮助——但至少你听了 someone 的意见。
  • @ŞivāSankĂr,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-08
  • 2015-03-12
相关资源
最近更新 更多