Skip to content
Advertisement

app.get() has 3 parameters, I need an explnation Node JS , express

I’m a noob. I have a question. I’m using passport-google-oauth20

app.get('/auth/google/secrets',
passport.authenticate('google',{failureRedirect: '/login'}),
function(req,res){
  res.redirect('/secrets');
});

as you can clearly see , this rout ( app.get() ) has 3 parameters, and this is the first time I used something like this, can anyone please explain the logic/theory behind this ?

normally I use

app.get('/somepage' , function(req,res,next){//something});

but in this special case, there are 3 parameters. can you provide me with any documentation for this specific situation ?

The code is perfectly fine, I just need an explnation .

Advertisement

Answer

app.get() accepts a minimum of two arguments as shown in the doc, but you can pass as many callbacks as you want (one or more):

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

Each callback you pass is executed in series one after the other. The second one doesn’t get executed until the first one calls next() in its handler and so on for the other ones.

This allows you to have middleware that is specific to just this route. In the case you show in your question, it’s inserting some middleware to require authentication before the main request handler is executed.

If that authentication fails, the middleware will send a response and the final callback will not be called. If the authentication passes, it will call next() and the final callback will then be executed.

Here’s a illustrative example:

app.get("/test", 
   (req, res, next) => {
     console.log("in first handler");
     next();
}, (req, res, next) => {
     console.log("in second handler");
     next();         
}, (req, res, next) => {
     console.log("in third handler, sending response");
     // sending response and not calling next()
     res.send("ok");
}, (req, res, next) => {
     // won't ever get here
     console.log("in final handler");
     res.send("hi");
});

This shows four request handlers being passed to an app.get(). The output from this in the debug console on the server will be:

in first handler
in second handler
in third handler, sending response

And, the response from this request will be:

ok

The fourth handler will not be called because the third handler does not call next(). Instead, it just sends a response to the request.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement