简体   繁体   English

表达js app.get回调函数

[英]express js app.get callback function

hi I am confused about the syntax of the get route function there seems to be 2 versions here is some example code 嗨,我对get route函数的语法感到困惑,似乎有2个版本,这里是一些示例代码

first one: 第一:

app.get('/users', function(req,res){
     ...
});

second one: 第二个:

app.get('users/:name', function(req,res,next){
     ...
     if(users[req.params.name])
      ....
     else
         next()
});

I am confused as to what is the next function in the second one. 我对第二个功能的下一个功能感到困惑。 And why it isn't necessary in the first one 以及为什么在第一个中没有必要

Thanks 谢谢

Back it up a bit and look at express as a middleware stack. 稍微备份一下,然后将Express视为中间件堆栈。 Literally, a stack. 从字面上看,是一个堆栈。

You have a series of app.use , app.get , and app.post calls. 您有一系列的app.useapp.getapp.post调用。 Together, they form a chain. 它们一起形成一条链。 When a request comes in, express figures out which middleware functions match the URL pattern and calls the first one along with a reference to the next one. 收到请求时,请明确指出哪些中间件功能与URL模式匹配,并调用第一个中间件功能以及对下一个中间件的引用。 This is how separate, independent middleware objects get linked. 这是链接独立的独立中间件对象的方式。

For example, there is a middleware that parses the query string and stores it as an object in req.query . 例如,有一个中间件可以解析查询字符串并将其作为对象存储在req.query There is a middleware that parses the Cookie header and creates cookie objects. 有一个中间件可以解析Cookie头并创建cookie对象。 There is a middleware that provides access logging. 有一个提供访问日志的中间件。 Again, these get linked together as a chain. 同样,这些被链接在一起成为一条链。 If the middleware functions are independent, they do their work and then pass control to the next link in the chain by calling next() . 如果中间件功能是独立的,则它们将执行其工作,然后通过调用next()将控制权传递到链中的下一个链接。

app.use(express.logger();
app.use(express.responseTime());
app.use(express.compress());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser());
app.use(express.session());
app.use(i18n.handle);
app.use(app.router);

The reason routes do not have to use next is because routes are generally the end of a chain. 路由不必使用next的原因是,路由通常位于链的末端。 There is nothing left to do after a route. 路线之后,无事可做。

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

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