Express —— Middleware and the middleware stack

原创转载请注明出处:http://agilestyle.iteye.com/blog/2339754

 

Middleware

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

The following figure shows the elements of a middleware function call:


 

The middleware stack

Web Server通常会监听request,解析request,并且发送response。Node运行环境首先会获取这些request并且将它们从原生字节转换为你可以处理的两个JavaScript对象:request(req)和response(res)。当仅仅使用Node.js,流程图如下所示。


 

这两个对象将会被送到一个你自己定义的JavaScript的Function中。你会自己解析req来确认用户想要什么,并且巧妙的处理res来准备你的响应。

过了一会儿,你将通过调用res.end来完成响应的编写。这个res.end告诉Node响应已经完成,可以准备发送了。Node运行环境首先将查看你对响应对象做了什么,然后将它转换成另外一束字节,最终发送给在网络上请求的用户。

在Node中,这两个对象仅仅是通过一个Function传递的。但是在Express中,这些对象是通过一系列Function传递的,称为middleware stack。Express将从stack中的第一个Function开始并且沿着Stack向下顺序执行,如下图所示。


 

每一个在Stack中的函数接收3个参数。第一个两个是req和res,它们通过Node提供;每个函数的第三个参数本身就是一个函数,按照惯例称为next。当next被调用,Express将运行Stack中的下一个函数,如下图所示。


 

最终,在Stack中的一个函数必须调用res.end,表示结束请求(在Express中,也可以调用其他的方法,比如:res.send或者res.sendFile,但是这些方法内部是调用res.end的)。你可以调用在middleware stack中的任意一个函数的res.end,但是只能调用一次,否则将报错。

 

Reference

http://expressjs.com/en/guide/writing-middleware.html

Manning.Express.in.Action.Node.applications.with.Express.and.its.companion.tools.2016

 

猜你喜欢

转载自agilestyle.iteye.com/blog/2339754