Home > front end >  next() is not used in Express, Node.js and Angular learning projects - is it right?
next() is not used in Express, Node.js and Angular learning projects - is it right?

Time:12-07

I had learned 2 MEAN courses (MongoDB, Express, Angular, Node.js) which creates a simple blog and in the both courses next() method is never used.

Is it OK? Both projects work properly.

Do I have to write code further without next() method or I have to start use it?

I have read that without 'return next()' a function can be called twice or something like that.

Please, advise.

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)
    }
})

CodePudding user response:

next() has specific uses when you wish to continue routing onto other request handlers. It is most commonly used in middleware. For example, here's a piece of middleware that logs the incoming request path and then continues routing onto other request handlers that might also match this particular request:

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

If, on the other hand, you are just writing a request handler that well just send a response and does not ever need to continue routing to other request handlers, then you do not need to declare or use next as in:

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

Do I have to write code further without next() method or I have to start use it?

If you never have any circumstances where you want to continue routing into other request handlers, then you do not need to use next().

I have read that without 'return next()' a function can be called twice or something like that.

That is not a correct interpretation of that question and answer. The point that is not being made very well there is that if you are using a call to next() AND you have code that could execute when the rest of your function runs, then you will need a return statement to stop the rest of your function from executing. This is most common in an if statement such as:

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");
});

In this case, the call to next() allows Express to continue routing to other request handlers, but it does NOT stop the execution of the rest of this function. To do that, you either have to turn this if into an if/else or you have to insert a return as I show. Otherwise, it will both call next() and call res.redirect("/login"); which is not what you want.


P.S. In a personal coding style comment, I don't use return next() because that programming structure implies that there's a meaningful return value from the call to next() that you want to return. There is no meaningful return value and, in fact, a request handler does not pay any attention to a returned value. So, even though it is less compact to code, I prefer to put the return; on the next line to not imply there is an actual return value being used here.

  • Related