一些 Connect 术语
以下是与 ConnectJS for NodeJS 相关的文档中不断使用的三个术语,但我并不完全理解:
1)视图和控制器
2)部分和集合
3)中间件
Here are three pieces of terminology used in documentation relating to ConnectJS for NodeJS that keeps getting used, but that I don't completely undertand:
1) views and controllers
2) partials and collections
3) Middleware
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让我们从下往上开始。
Level 0:内置http模块
一开始,有node.js内置的http。服务器由 Ryan Dahl 编写。您编写一个
function(req, res)
,Node 将在每次接受新连接时调用您的函数:级别 1:连接
Connect,由 Tim Caswell 编写,只是 http.Server 的一个子类,它使您可以更轻松地组织代码。您无需编写处理每个请求的单个回调,而是将一些中间件链接在一起。每个中间件都是一个
function(req, res, next)
,如果可能的话,它会处理请求,如果没有完成处理用户的请求,则调用next(error)
。中间件处理程序按照其使用
顺序调用;您应该在最后调用包罗万象的app.use(connect.errorHandler())
。一个重要的中间件是路由器,它允许您根据 URL 路径的模式过滤某些中间件。 路由模式的语法基于 ruby 的 Sinatra 路由。当我使用过滤器
/hello/:name
时,req.params.name
将被设置为 URL 的匹配部分。在 Connect 中,每个处理程序都是中间件!您可以使用任何您需要的功能,例如 bodyParser 或 cookieParser,并且您自己的业务逻辑也是具有相同签名
function(req, res, next)
的中间件函数。 connect 主页提供了内置中间件的列表。第 2 级:Express.js
Express 的 http 服务器由 TJ Holowaychuk 编写,它又是 Connect 的子类,它更加强调 Sinatra 风格。在 Connect 中,没有您不要求的魔法,但在 Express 中,路由器和 qs 解析器(设置
req.query
)会自动使用
。路由器语法被清理;您可以直接调用app.get
、app.post
等(并且路由器位于第一次调用处),而不是将它们放在函数中。Express 还包含许多其他详细记录的功能和辅助函数来扩展应用程序、请求和资源。
Express 的一项功能是
res.render
,它使用模板引擎渲染给定的模板文件(相对于app.set('views')
或 $PWD/views)由扩展隐含,以及res.partial
,它在集合的每个元素上调用 render(它只是任何类似数组的对象)。但我还没有使用过这个可选功能;如果您不喜欢express的模板,您可以自己res.send
数据。Let's start from the bottom up.
Level 0: built-in http module
In the beginning, there is node.js's built-in http.Server written by Ryan Dahl. You write a
function(req, res)
, and Node will call your function each time a new connection is accepted:Level 1: Connect
Connect, written by Tim Caswell, is simply a subclass of http.Server that makes it easier to organize your code. Instead of writing a single callback that handles every request, you chain together some middleware. Each middleware is a
function(req, res, next)
that handles the request if possible, or callsnext(error)
if it did not finish handling the user's request. The middleware handlers are called in the order of theiruse
; you should call the catch-allapp.use(connect.errorHandler())
at the end.One important middleware is the router, which allows you to filter some middleware based on a pattern of the URL path. The syntax for the route patterns is based on ruby's Sinatra routes. When I use the filter
/hello/:name
,req.params.name
will be set to the matching part of the URL.In Connect, every handler is middleware! You use whichever functionality you need like bodyParser or cookieParser, and your own business logic is also a middleware function with the same signature
function(req, res, next)
. The connect homepage gives a list of the built-in middleware.Level 2: Express.js
Express's http server, written by TJ Holowaychuk, is in turn a subclass of Connect that forces the Sinatra style more. In Connect, there was no magic you didn't ask for, but in Express, the router and qs parser (which sets
req.query
) are automaticallyuse
d. The router syntax is cleaned up; you callapp.get
,app.post
, etc. directly (and the router is positioned at the first call) rather than putting them inside a function.Express also contains many other well-documented features and helper functions to extend app, req, and res.
One feature of Express is
res.render
, which renders the given template file (relative toapp.set('views')
or $PWD/views) using the template engine implied by the extension, andres.partial
, which calls render on each element of a collection (which is just any arraylike object). But I haven't used this optional feature; if you don't care for express's templates you can justres.send
data yourself.以下是一些评论。如果您有更具体的问题,我们可以尝试解决。
1) 视图和控制器
视图只是指可用于呈现响应的模板,通常是 HTML,但也可以是纯文本或其他格式。有许多不同的模板语法和系统。有些可以在 NodeJS 和 Web 浏览器中工作。这就是视图的全部内容。
控制器是 MVC 设计模式中的“C”,负责充当视图和模型之间的中介。它们基本上是处理一些基本事情的粘合剂,例如不属于模型代码的格式选择。
2)部分和集合
(旁注,这些实际上是 Express.js 的一部分,不是 Connect,但它们 Partials是
一个文档模板,代表文档的一小部分或片段,而不是完整的 HTML 文档。部分可以被其他模板包含,并且通常被多个包含模板重复使用。收藏与它们齐头并进。例如,您可能有一个部分来显示“总统”对象,并且在该部分中您可以标记照片、他担任总统的日期、政党等。只要您想要显示“总统”记录/对象。如果您有多个“总统”对象的集合,“集合”为您提供了一种简单的方法来表达“为该列表中的每个总统对象渲染总统部分”。
3) 中间件
connect 处理响应 HTTP 请求的方式是通过一系列称为中间件的函数来路由请求。每个中间件功能都遵循基本 API
(req, res, next)
和一些行为要求。每个中间件都可以执行一个特定的处理,然后在完成后调用next()
告诉 connect 继续执行链中的下一个中间件函数。 Connect 附带了一堆中间件模块,您可以在 github 上看到这些模块。中间件可以为所欲为。例如,解析 JSON 请求正文、在文件系统中搜索要提供的匹配静态文件、检查会话 cookie、记录到日志文件等。这种设计使得重用代码以及以新颖的组合方式组合单独的中间件功能变得非常容易。一些中间件函数处理解析和处理请求,一些处理生成响应。通常,您可以找到执行大量请求处理(解析、记录、解码、转换等)的现有中间件函数,并且您提供自己的中间件来实际呈现响应,这通常也是链中的最后一个中间件。Here are some comments. If you have more specific questions, we can try to address them.
1) views and controllers
Views just means a template that can be used to render a response, which is usually HTML but could be plain text or some other format. There are many different templating syntaxes and systems out there. Some work in NodeJS as well as in web browsers. That's all there is to views.
Controllers are the "C" in the MVC design pattern and are responsible as an intermediary between views and models. They are basically the glue that handles some basic things like formatting choices that don't belong in the model code.
2) partials and collections
(Side comment, these are really part of Express.js, not Connect, but they are sibling libraries)
Partials is a document template representing a small portion or snippet of a document, as opposed to a complete HTML document. Partials can be included by other templates and are often re-used by multiple containing templates. Collections go hand in hand with them. For example, you might have a partial to display a "President" object and in that partial you'd have markup for a photo, dates he served as president, political party, etc. You could use that same partial throughout your site whenever you wanted to display a "President" record/object. If you had a collection of several "President" objects, "collections" give you an easy way to say "render a president partial for each president object in this list".
3) middleware
The way connect handles responding to HTTP requests is to route the request through a series of functions called middleware. Each middleware function adheres to a basic API of
(req, res, next)
and a few behavioral requirements. Each piece of middleware can do one specific bit of processing, then when it's done, callnext()
to tell connect to move on to the next middleware function in the chain. Connect comes with a bunch of middleware modules which you can see on github. Middleware can do whatever it wants. For example, parse JSON request bodies, search the filesystem for a matching static file to serve, check for session cookies, log to a log file, and so on. This design makes it really easy to re-use code as well as to combine separate middleware functions in novel combinations. Some middleware functions deal with parsing and processing the request, some deal with generating the response. Typically you can find existing middleware functions that do a lot of request processing (parsing, logging, decoding, converting, etc), and you provide your own middleware to actually render the response, which is also usually the last middleware in the chain.