Nginx NodeJS Express - Router 5
http://www.codes51.com/article/detail_2787757_5.html
3. Middleware
An Express application is essentially a stack of middleware which are executed serially.
(express应用其实就是由一系列顺序执行的Middleware组成。)
A middleware is a function with access to the request object (req), the response object (res),
and the next middleware in line in the request-response cycle of an Express application.
It is commonly denoted by a variable named next. Each middleware has the capacity to execute any code,
make changes to the request and the reponse object, end the request-response cycle, and call the
next middleware in the stack. Since middleware are execute serially, their order of inclusion is
important.(中间件其实就是一个访问express应用串入的req,res,nex参数的函数,这个函数可以访问任何通过req,res传入的资源。)
If the current middleware is not ending the request-response cycle, it is important to call next() to
pass on the control to the next middleware, else the request will be left hanging.
(如果当前中间件没有完成对网页的res响应 ,还可以通过next把router 留给下一个middleware继续执行)
With an optional mount path, middleware can be loaded at the application level or at the router level.
Also, a series of middleware functions can be loaded together, creating a sub-stack of middleware system
at a mount point.
路由的产生是通过HTTP的各种方法(GET, POST)产生的,Middleware可以跟router路径跟特定的HTTP方法绑定,
也可以跟所有的方法绑定。
3.1 通过express应用的use(all),把Middleware同router路径上的所有HTTP方法绑定:
1 app.use(function (req, res, next) {
2 console.log('Time: %d', Date.now());
3 next();
4 })
3.2 通过express应用的http.verb,把Middleware同router路径上的特定的HTTP方法绑定:
1 app.get('/', function(req, res){
2 res.send('hello world');
3 });
4
5
6 app.post('/', function(req, res){
7 res.send('hello world');
8 });
posted on 2017-09-14 15:30 fanbird2008 阅读(42) 评论(0) 收藏 举报
浙公网安备 33010602011771号