1

I meet a problem when tracing the node.js express application. Following is the sample people often using:

app.get('/api/users', function(req, res) {
    const user_id = req.query.id;
    const token = req.query.token;
    const geo = req.query.geo;

    res.send({
        'user_id': user_id,
        'token': token,
        'geo': geo
    });
}); 

However, in the csurf case, the authentication function is this:

app.post('/process', parseForm, csrfProtection, function(req, res) {
    res.send('data is being processed')
})

The problem is what the definition of express app function parameters like get or post, it seems very different from the usually usage scenario like the first case above, and the office document in express doesn't explain the four parameters situation. Any instruction is highly appreciated, thanks a lot.

abramhum
  • 443
  • 2
  • 8
  • 20
  • https://expressjs.com/en/4x/api.html#app.post.method and https://expressjs.com/en/4x/api.html#middleware-callback-function-examples – Phil Apr 14 '23 at 03:48
  • 3
    Does this answer your question? [Chaining multiple pieces of middleware for specific route in ExpressJS](https://stackoverflow.com/questions/31928417/chaining-multiple-pieces-of-middleware-for-specific-route-in-expressjs) – Phil Apr 14 '23 at 03:50

1 Answers1

2

parseForm, csrfProtection and your function(req,res) are all request handlers/middleware and you can have as many as you need (minimum 1), passed one after another as arguments to app.get(), app.post() or any app.xxx() verb.

They are called on after the other and they advance to the next one, when the previous one calls next(). They are all passed the arguments (req, res, next). This is how a middleware chain works.

So, in this specific handler:

app.post('/process', parseForm, csrfProtection, function(req, res) {
    res.send('data is being processed')
});

It will first call parseForm(req, res, next) and when/if that calls next(), it will then call csrfProtection(req, res, next) and when/if that calls next(), it will then call your function(req, res). FYI, next is actually passed to that too, you just don't have to declare it if you're not going to use it.

Whichever one of these wants to end the response sends a response with something like res.send() and then does not call next() and the response will be done and the chain will end. This can be done from anywhere in the chain.


You will see in the Express doc that it shows:

app.post(path, callback [, callback ...])

That notation indicates that you can have one or more callbacks passed after the path. parseForm, csrfProtection and function(req, res) are all callbacks that matches this calling signature.

jfriend00
  • 683,504
  • 96
  • 985
  • 979