Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in express how multiple callback works in app.get

I am newbie in node so please forgive me if i am not getting obvious. In node.js express application for app.get function we typically pass route and view as parameters e.g.

app.get('/users', user.list);

but in passport-google example I found that they are calling it as

app.get('/users', ensureAuthenticated, user.list);

where ensureAuthenticated is a function

function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) { return next(); }
    res.redirect('/login')
}

In short this means there are multiple callbacks which while running are called in series. i tried adding couple of more functions to make it look like

app.get('/users', ensureAuthenticated, dummy1, dummy2, user.list);

and i found ensureAuthenticated, dummy1, dummy2, user.list is getting called in series.

for my specific requirement i find calling functions sequentially in above form is quite elegant solution rather that using async series. can somebody explain me how it really works and how i can implement similar functionality in general.

like image 725
Tushar Jambhekar Avatar asked Mar 09 '14 17:03

Tushar Jambhekar


People also ask

Which are the two callback functions attached to the route that will be called when we browse to the node URL?

put() , and so on. PATH is a path on the server. HANDLER is the callback function executed when the route and method are matched.

What is callback function in Express?

What is Callback? Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are written in such a way that they support callbacks.

How do Middlewares work in Express?

Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.


1 Answers

In Express, each argument after the path is called in sequence. Usually, this is a way of implementing middleware (as you can see in the example you provided).

app.get('/users', middleware1, middleware2, middleware3, processRequest);

function middleware1(req, res, next){
    // perform middleware function e.g. check if user is authenticated

    next();  // move on to the next middleware

    // or

    next(err);  // trigger error handler, usually to serve error page e.g. 403, 501 etc
}
like image 118
takinola Avatar answered Sep 20 '22 08:09

takinola