【问题标题】:next() is not used in Express, Node.js and Angular learning projects - is it right?在 Express、Node.js 和 Angular 学习项目中不使用 next() - 对吗?
【发布时间】:2022-01-12 06:42:33
【问题描述】:

我学习了 2 门 MEAN 课程(MongoDB、Express、Angular、Node.js),它们创建了一个简单的博客,并且在这两门课程中从未使用过 next() 方法。

可以吗? 两个项目都能正常运行。

我必须在没有 next() 方法的情况下进一步编写代码还是必须开始使用它?

我读过没有'return next()' 的函数可以是called twice 或类似的东西。

请指教。

router.post('/dashboard', passport.authenticate('jwt', { session: false }),
(req, res) => {

    try {
        let newPost = new Post({
            category: req.body.category,
            title: req.body.title,
            photo: req.body.photo,
            text: req.body.text,
            author: req.body.author,
            date: req.body.date
        });

        Post.addPost(newPost, (err, user) => {
            if (err) {
                res.json({success: false, msg: `Post has not been added. ${err}`})
            } else {
                res.json({success: true, msg: 'Post was added.'})
            }
        })
    } catch (err) {
       const error = (res, error) => {
            res.status(500).json({
                success: false,
                message: error.message ? error.message : error
            })
       }

       console.log('error routes/auth POST', res, error)
    }
})

【问题讨论】:

    标签: node.js express mean next


    【解决方案1】:

    next() 在您希望继续路由到其他请求处理程序时具有特定用途。它最常用于中间件。例如,这是一个中间件,它记录传入的请求路径,然后继续路由到可能也匹配此特定请求的其他请求处理程序:

    app.use((req, res, next) => {
        console.log(`path=${req.path}, method=${req.method}`);
        next();
    });
    

    另一方面,如果您只是编写一个请求处理程序,它只是发送响应并且不需要继续路由到其他请求处理程序,那么您不需要声明或使用next,如:

    app.get("/greeting", (req, res) => {
        res.send("hi");
    });
    

    我必须在没有 next() 方法的情况下进一步编写代码还是必须开始使用它?

    如果您在任何情况下都不想继续路由到其他请求处理程序,那么您不需要使用next()

    我已经读过,如果没有'return next()',一个函数可以被调用两次或类似的东西。

    这不是对that question and answer 的正确解释。没有做得很好的一点是,如果您正在使用对 next() 的调用并且您的代码可以在函数的其余部分运行时执行,那么您将需要一个 return 语句来停止其余部分你的功能从执行。这在if 语句中最常见,例如:

    app.use((req, res, next) => {
        // check for auth and continue routing if authenticated already
        if (req.session && req.session.isAuthenticated) {
            next();
            return;
        }
        res.redirect("/login");
    });
    

    在这种情况下,对next() 的调用允许 Express 继续路由到其他请求处理程序,但它不会停止该函数其余部分的执行。为此,您要么必须将此if 转换为if/else,要么必须插入return,如我所示。否则,它会同时调用next() 和调用res.redirect("/login");,这不是你想要的。


    附:在个人编码风格的评论中,我不使用return next(),因为该编程结构意味着您想要返回的对next() 的调用有一个有意义的返回值。没有有意义的返回值,事实上,请求处理程序并不关注返回值。因此,即使代码不那么紧凑,我更喜欢将 return; 放在下一行,而不是暗示这里使用了实际的返回值。

    【讨论】:

      猜你喜欢
      • 2018-06-13
      • 2021-08-27
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多