Вопрос

I am working through an excellent tutorial on using the Node.js package Passport (link) for user authentication, and I ran into a piece of code that I really don't understand:

app.get('/profile', isLoggedIn, function(req, res) {
    res.render('profile.ejs', {
        user : req.user // get the user out of session and pass to template
    });
});

My question is with the isLoggedIn parameter. I looked at the official site, and did some google searches, but nowhere does it say that you can pass three parameters into app.get. I've only ever seen two. What is this third (optional, I assume) parameter?

I'm not asking about the isLoggedIn itself, but rather, about the fact that it's a third parameter I've never seen passed into app.get() before.

Это было полезно?

Решение

It's called middleware, and it's called before the third parameter (the callback).

Middleware functions examples: access checks, check to see if user is logged in before passing resources, and such.

Другие советы

It's in the express documentation: http://expressjs.com/en/5x/api.html#app.get

The syntax is: app.get(path, callback [, callback ...]) i.e. app.get(path, ...callback)

The syntax includes taking in a path as the first parameter, followed by as many middleware (having access to the request and response) callback functions as you desire. It's not limited to one. They are asynchronous and chained together by calling the next() parameter.

function callbackOne(req, res, next) {
    //some code
    next();
}
function callbackTwo(req, res, next) {
    //some code
    res.render();
}
app.get(path, callbackOne, callbackTwo)

So, in your case, the isLoggedIn parameter is simply just another middleware function that eventually calls next() if the user is logged in to bring execution to the third parameter.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top