简体   繁体   English

带有 Express 的 Node.js 中的 app.get() 第三个参数

[英]app.get() third parameter in Node.js with Express

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:我正在学习使用 Node.js 包 Passport( 链接)进行用户身份验证的优秀教程,但我遇到了一段我真的不明白的代码:

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.我的问题是isLoggedIn参数。 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 .我查看了官方网站,并进行了一些谷歌搜索,但没有任何地方说您可以将三个参数传递给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.我不是在问isLoggedIn本身,而是在问它是我以前从未见过传递给app.get()的第三个参数这一事实。

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它在快速文档中: http : //expressjs.com/en/5x/api.html#app.get

The syntax is: app.get(path, callback [, callback ...]) ie app.get(path, ...callback)语法是: app.get(path, callback [, callback ...])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.它们是异步的并通过调用 next() 参数链接在一起。

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.因此,在您的情况下, isLoggedIn 参数只是另一个中间件函数,如果用户登录以将执行带到第三个参数,则最终调用 next() 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM