node.js Express app.get 文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12718962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:24:38  来源:igfitidea点击:

Express app.get documentation

node.jsexpressmiddleware

提问by ThomasReggi

I am looking for some documentation on the app.getfunction of express.js.

我正在寻找app.get有关 express.js 功能的一些文档。

app.get(
    '/path', 
    middleware(),
    function(req, res) {
        res.redirect('/');
    }
);

The example above takes three parameters. The normal docs only show two. I'm interested in what this middle param does and how to use it.

上面的示例采用三个参数。普通文档只显示两个。我对这个中间参数的作用以及如何使用它感兴趣。

回答by JohnnyHK

The docs for that are part of the app.METHODdocumentation, where getis one of the supported HTTP methods.

对于该文档是的一部分app.METHOD的文档,其中,get是受支持的HTTP方法之一。

The second, optional parameter, is called middleware (and you can pass an array of middleware functions). This is a function that's called before the third parameter callback (the actual route handler) and the responsibility of a middleware function is to allow your code to follow the DRY (don't repeat yourself) principle.

第二个可选参数称为中间件(您可以传递一组中间件函数)。这是在第三个参数回调(实际路由处理程序)之前调用的函数,中间件函数的职责是让您的代码遵循 DRY(不要重复自己)原则。

Example of middleware functions are permissions checks, access validations, validation of sessions (if user is not in logged in, take him to a log in page), and such.

中间件功能的示例是权限检查、访问验证、会话验证(如果用户未登录,将他带到登录页面)等。

Since several routes might desire the same behavior, you use a middleware so that you don't have to write the same code several times.

由于多个路由可能需要相同的行为,因此您可以使用中间件,这样您就不必多次编写相同的代码。