Tara Roys
Tara Roys

Reputation: 1836

Execution order of callbacks in Express Post function

I am having trouble with [express's route handing methods], specifically a Post function.
(http://expressjs.com/api.html#app.VERB)

I am trying to parse through a piece of code from this passport example

app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
  function(req, res) {
  res.redirect('/');
});

The express documentation says

multiple callbacks are given, all are treated equally and behave just like middleware.

My questions is, is the following statement accurate:

middleware is like a bunch of tubes linked together. The middleware that comes first is the middleware that is listed first. If data is water, it will flow through the pipe that is listed first.

The same is true for the callbacks in route handing methods: the callbacks are pipes linked together, and if you pour data through these 'pipes', you are pouring it through the first callback listed and then the second callback in sequence. Is that true?

As a followup question, what are these callbacks supposed to return? Is the first callback returning a response, which the second callback recieves and treats as a request? what is supposed to come out of the pipe, and can I stick it into the second pipe?

Upvotes: 4

Views: 2245

Answers (1)

Renato Gama
Renato Gama

Reputation: 16579

Doesn't matter what the callbacks return in this case. They are invoking the next function (the third parameter that is not defined in this specific passport example). When next function is called then the next middleware in sequence is invoked with the same parameters as the first (same req, same res)

Say you have this code

function myFirstMiddleware(req, res, next) {//note the third parameter
    //you can change req and res objects
    next();
}

function secondMiddlewareInTheSequence(req, res, next) {
    //here you get the changes you've done to req and res since they are
    //the same objects
    res.end();
}

app.post('/', myFirstMiddleware, secondMiddlewareInTheSequence);

What passport.authenticate does internally is to call next if your request is properly authenticated, so your middleware is passed control.

You may even want not to pass the control to further middlewares, based on a given condition (pretty much what passport does), like this.

function checkSecret(req, res, next) {
    if(req.query && req.query.secret === '42') {
        console.log('you are allowed to pass!');
        next();
    } else {
        console.log('you shall not pass!');
        res.status(403).end();
    }
}

The above function if placed before any other middleware would prevent requests not containing the secret to continue!

Upvotes: 3

Related Questions