Node.js 的 Connect、Express 和“中间件”是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5284340/
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
What is Node.js' Connect, Express and "middleware"?
提问by tillda
Despite knowing JavaScript quite well, I'm confused what exactlythese three projects in Node.js ecosystem do. Is it something like Rails' Rack? Can someone please explain?
尽管对 JavaScript 非常了解,但我对Node.js 生态系统中的这三个项目到底做了什么感到困惑。是不是类似于 Rails 的 Rack?有人可以解释一下吗?
回答by Trevor Burnham
[Update:As of its 4.0 release, Express no longer uses Connect. However, Express is still compatible with middleware written for Connect. My original answer is below.]
[更新:从 4.0 版本开始,Express 不再使用 Connect。但是,Express 仍然兼容为 Connect 编写的中间件。我的原始答案如下。]
I'm glad you asked about this, because it's definitely a common point of confusion for folks looking at Node.js. Here's my best shot at explaining it:
我很高兴你问到这个问题,因为对于查看 Node.js 的人来说,这绝对是一个常见的困惑点。这是我最好的解释:
Node.js itself offers an httpmodule, whose
createServermethod returns an object that you can use to respond to HTTP requests. That object inherits thehttp.Serverprototype.Connectalso offers a
createServermethod, which returns an object that inherits an extended version ofhttp.Server. Connect's extensions are mainly there to make it easy to plug in middleware. That's why Connect describes itself as a "middleware framework," and is often analogized to Ruby's Rack.Expressdoes to Connect what Connect does to the http module: It offers a
createServermethod that extends Connect'sServerprototype. So all of the functionality of Connect is there, plusview rendering and a handy DSL for describing routes. Ruby's Sinatra is a good analogy.Then there are other frameworks that go even further and extend Express! Zappa, for instance, which integrates support for CoffeeScript, server-side jQuery, and testing.
Node.js 本身提供了一个http模块,它的
createServer方法返回一个对象,您可以使用它来响应 HTTP 请求。该对象继承了http.Server原型。Connect还提供了一个
createServer方法,该方法返回一个对象,该对象继承了http.Server. Connect 的扩展主要是为了方便插入中间件。这就是为什么 Connect 将自己描述为“中间件框架”,并且经常被类比为 Ruby 的 Rack。Express对 Connect 的作用与 Connect 对 http 模块的作用相同:它提供了
createServer一种扩展 ConnectServer原型的方法。所以 Connect 的所有功能都在那里,加上视图渲染和用于描述路由的方便的 DSL。Ruby 的 Sinatra 是一个很好的类比。然后还有其他框架可以更进一步扩展 Express!例如,Zappa集成了对 CoffeeScript、服务器端 jQuery 和测试的支持。
Here's a concrete example of what's meant by "middleware": Out of the box, none of the above serves static files for you. But just throw in connect.static(a middleware that comes with Connect), configured to point to a directory, and your server will provide access to the files in that directory. Note that Express provides Connect's middlewares also; express.staticis the same as connect.static. (Both were known as staticProvideruntil recently.)
这是“中间件”含义的一个具体示例:开箱即用,以上没有一个为您提供静态文件。但是只要加入connect.static(Connect 附带的中间件),配置为指向一个目录,您的服务器将提供对该目录中文件的访问权限。请注意,Express 还提供了 Connect 的中间件;express.static与 相同connect.static。(staticProvider直到最近,两者都被称为。)
My impression is that most "real" Node.js apps are being developed with Express these days; the features it adds are extremely useful, and all of the lower-level functionality is still there if you want it.
我的印象是,现在大多数“真正的”Node.js 应用程序都是用 Express 开发的。它添加的功能非常有用,如果您需要,所有较低级别的功能仍然存在。
回答by basarat
The accepted answer is really old (and now wrong). Here's the information (with source) based on the current version of Connect (3.0) / Express (4.0).
接受的答案真的很旧(现在是错误的)。这是基于当前版本的 Connect (3.0) / Express (4.0) 的信息(带来源)。
What Node.js comes with
Node.js 附带什么
http/ httpscreateServerwhich simply takes a callback(req,res) e.g.
http/ httpscreateServer只需要一个回调(req,res) 例如
var server = http.createServer(function (request, response) {
// respond
response.write('hello client!');
response.end();
});
server.listen(3000);
What connect adds
什么连接添加
Middlewareis basically any software that sits between your application code and some low level API. Connect extends the built-in HTTP server functionality and adds a plugin framework. The plugins act as middleware and hence connect is a middleware framework
中间件基本上是位于您的应用程序代码和一些低级 API 之间的任何软件。Connect 扩展了内置的 HTTP 服务器功能并添加了一个插件框架。插件充当中间件,因此 connect 是一个中间件框架
The way it does that is pretty simple (and in fact the code is really short!). As soon as you call var connect = require('connect'); var app = connect();you get a function appthat can:
这样做的方式非常简单(实际上代码很短!)。只要你打电话,var connect = require('connect'); var app = connect();你就会得到一个函数app,它可以:
- Can handle a request and return a response. This is because you basically get this function
- Has a member function
.use(source) to manage plugins(that comes from herebecause of this simple line of code).
Because of 1.) you can do the following :
由于 1.) 您可以执行以下操作:
var app = connect();
// Register with http
http.createServer(app)
.listen(3000);
Combine with 2.) and you get:
与 2.) 结合,您将得到:
var connect = require('connect');
// Create a connect dispatcher
var app = connect()
// register a middleware
.use(function (req, res, next) { next(); });
// Register with http
http.createServer(app)
.listen(3000);
Connect provides a utility function to register itself with httpso that you don't need to make the call to http.createServer(app). Its called listenand the code simply creates a new http server, register's connect as the callback and forwards the arguments to http.listen. From source
Connect 提供了一个实用程序函数来注册自己,http这样您就不需要调用http.createServer(app). 它被调用listen,代码简单地创建一个新的 http 服务器,将连接注册为回调并将参数转发到http.listen. 从源头
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, you can do:
所以,你可以这样做:
var connect = require('connect');
// Create a connect dispatcher and register with http
var app = connect()
.listen(3000);
console.log('server running on port 3000');
It's still your good old http.createServerwith a plugin framework on top.
http.createServer在顶部有一个插件框架仍然是你的好老。
What ExpressJS adds
ExpressJS 添加了什么
ExpressJS and connect are parallel projects. Connect is justa middleware framework, with a nice usefunction. Express does not depend on Connect(see package.json). However it does the everything that connect does i.e:
ExpressJS 和 connect 是并行项目。Connect只是一个中间件框架,use功能不错。Express 不依赖于 Connect(参见 package.json)。然而,它完成了连接所做的一切,即:
- Can be registered with
createServerlike connect since it too is just a function that can take areq/respair (source). - A use function to register middleware.
- A utility
listenfunction to register itself with http
- 可以使用
createServerlike connect注册,因为它也只是一个可以接受req/res对(source)的函数。 - 一个使用函数来注册中间件。
- 一个
listen向http 注册自己的实用函数
In addition to what connect provides (which express duplicates), it has a bunch of more features. e.g.
除了 connect 提供的功能(表示重复项)之外,它还具有更多功能。例如
- Has view engine support.
- Has top level verbs (get/post etc.) for its router.
- Has application settingssupport.
- 有视图引擎支持。
- 具有用于其 router 的顶级动词(get/post 等)。
- 有应用程序设置支持。
The middleware is shared
中间件是共享的
The usefunction of ExpressJS andconnect is compatible and therefore the middleware is shared. Both are middleware frameworks, express just has more than a simple middleware framework.
useExpressJS和connect的功能是兼容的,因此中间件是共享的。两者都是中间件框架,express不仅仅是一个简单的中间件框架。
Which one should you use?
你应该使用哪一个?
My opinion: you are informed enough ^based on above^ to make your own choice.
我的意见:你被告知足够多^基于上述^做出自己的选择。
- Use
http.createServerif you are creating something like connect / expressjs from scratch. - Use connect if you are authoring middleware, testing protocols etc. since it is a nice abstraction on top of
http.createServer - Use ExpressJS if you are authoring websites.
- 使用
http.createServer如果要创建像从头连接/ expressjs。 - 如果您正在编写中间件、测试协议等,请使用 connect,因为它是一个很好的抽象
http.createServer - 如果您正在创作网站,请使用 ExpressJS。
Most people should just use ExpressJS.
大多数人应该只使用 ExpressJS。
What's wrong about the accepted answer
接受的答案有什么问题
These might have been true as some point in time, but wrong now:
这些在某个时间点可能是正确的,但现在是错误的:
that inherits an extended version of http.Server
继承了 http.Server 的扩展版本
Wrong. It doesn't extend it and as you have seen ... uses it
错误的。它没有扩展它,正如你所看到的......使用它
Express does to Connect what Connect does to the http module
Express 对 Connect 的作用是 Connect 对 http 模块的作用
Express 4.0 doesn't even depend on connect. see the current package.json dependencies section
Express 4.0 甚至不依赖于连接。查看当前的 package.json 依赖项部分
回答by Juan Lanus
node.js
节点.js
Node.js is a javascript motor for the server side.
In addition to all the js capabilities, it includes networking capabilities (like HTTP), and access to the file system.
This is different from client-side js where the networking tasks are monopolized by the browser, and access to the file system is forbidden for security reasons.
Node.js 是服务器端的 javascript 引擎。
除了所有 js 功能外,它还包括网络功能(如 HTTP)和对文件系统的访问。
这与客户端 js 不同,客户端 js 的网络任务由浏览器垄断,出于安全原因禁止访问文件系统。
node.js as a web server: express
node.js 作为 Web 服务器:express
Something that runs in the server, understands HTTP and can access files sounds like a web server. But it isn't one.
To make node.js behave like a web server one has to program it: handle the incoming HTTP requests and provide the appropriate responses.
This is what Express does: it's the implementation of a web server in js.
Thus, implementing a web site is like configuring Express routes, and programming the site's specific features.
在服务器中运行、理解 HTTP 并且可以访问文件的东西听起来像一个网络服务器。但它不是一个。
要使 node.js 表现得像 Web 服务器,必须对其进行编程:处理传入的 HTTP 请求并提供适当的响应。
这就是 Express 所做的:它是用 js 实现的 Web 服务器。
因此,实现一个网站就像配置 Express 路由,并对网站的特定功能进行编程。
Middleware and Connect
中间件和连接
Serving pages involves a number of tasks. Many of those tasks are well known and very common, so node's Connectmodule (one of the many modules available to run under node) implements those tasks.
See the current impressing offering:
服务页面涉及许多任务。其中许多任务是众所周知且非常常见的,因此 node 的Connect模块(可在 node 下运行的众多模块之一)实现了这些任务。
查看当前令人印象深刻的产品:
- loggerrequest logger with custom format support
- csrfCross-site request forgery protection
- compressGzip compression middleware
- basicAuthbasic http authentication
- bodyParserextensible request body parser
- jsonapplication/json parser
- urlencodedapplication/x-www-form-urlencoded parser
- multipartmultipart/form-data parser
- timeoutrequest timeouts
- cookieParsercookie parser
- sessionsession management support with bundled MemoryStore
- cookieSessioncookie-based session support
- methodOverridefaux HTTP method support
- responseTimecalculates response-time and exposes via X-Response-Time
- staticCachememory cache layer for the static() middleware
- staticstreaming static file server supporting Range and more
- directorydirectory listing middleware
- vhostvirtual host sub-domain mapping middleware
- faviconefficient favicon server (with default icon)
- limitlimit the bytesize of request bodies
- queryautomatic querystring parser, populating req.query
- errorHandlerflexible error handler
- 具有自定义格式支持的记录器请求记录器
- csrf跨站请求伪造保护
- compressGzip 压缩中间件
- basicAuth基本 http 身份验证
- bodyParser可扩展的请求正文解析器
- json应用程序/json 解析器
- urlencoded应用程序/x-www-form-urlencoded 解析器
- 多部分多部分/表单数据解析器
- 超时请求超时
- cookieParsercookie 解析器
- 使用捆绑的 MemoryStore 支持会话会话管理
- cookieSession基于 cookie 的会话支持
- methodOverride虚假 HTTP 方法支持
- responseTime计算响应时间并通过 X-Response-Time 公开
- staticCache用于 static() 中间件的内存缓存层
- 支持 Range 等的静态流静态文件服务器
- 目录目录列表中间件
- vhost虚拟主机子域映射中间件
- favicon高效的 favicon 服务器(带有默认图标)
- 限制请求主体的字节大小
- 查询自动查询字符串解析器,填充 req.query
- errorHandler灵活的错误处理程序
Connect is the framework and through it you can pick the (sub)modules you need.
The Contrib Middlewarepage enumerates a long list of additional middlewares.
Express itself comes with the most common Connect middlewares.
Connect 是框架,通过它您可以选择您需要的(子)模块。
该的Contrib中间件页列举的另外一个长长的清单中间件。
Express 本身带有最常见的 Connect 中间件。
What to do?
该怎么办?
Install node.js.
Node comes with npm, the node package manager.
The command npm install -g expresswill download and install express globally (check the express guide).
Running express fooin a command line (not in node) will create a ready-to-run application named foo. Change to its (newly created) directory and run it with node with the command node <appname>, then open http://localhost:3000and see.
Now you are in.
安装 node.js。
Node 附带npm,即节点包管理器。
该命令npm install -g express将全局下载并安装 express(查看express 指南)。
运行express foo在命令行(而不是在节点)将创建一个随时可以运行的应用程序名为foo。切换到它的(新创建的)目录并使用 node 命令运行它node <appname>,然后打开http://localhost:3000并查看。现在你在。
回答by yojimbo87
Connect offers a "higher level" APIs for common HTTP server functionality like session management, authentication, logging and more. Express is built on top of Connect with advanced (Sinatra like) functionality.
Connect 为常见的 HTTP 服务器功能(如会话管理、身份验证、日志记录等)提供“更高级别”的 API。Express 建立在 Connect 之上,具有高级(类似 Sinatra)的功能。
回答by Suraj Kumar Yadav
Node.jsitself offers an HTTP module, whose createServermethod returns an object that you can use to respond to HTTP requests. That object inherits the http.Serverprototype.
Node.js它本身提供了一个 HTTP 模块,它的createServer方法返回一个对象,您可以使用它来响应 HTTP 请求。该对象继承了http.Server原型。
回答by Vic
Related information, especially if you are using NTVS for working with the Visual Studio IDE. The NTVS adds both NodeJS and Express tools, scaffolding, project templates to Visual Studio 2012, 2013.
相关信息,尤其是当您使用 NTVS 来处理 Visual Studio IDE 时。NTVS 将 NodeJS 和 Express 工具、脚手架、项目模板添加到 Visual Studio 2012、2013。
Also, the verbiage that calls ExpressJS or Connect as a "WebServer" is incorrect. You can create a basic WebServer with or without them. A basic NodeJS program can also use the http module to handle http requests, Thus becoming a rudimentary web server.
此外,将 ExpressJS 或 Connect 称为“WebServer”的说法是不正确的。您可以使用或不使用它们创建一个基本的 WebServer。一个基本的 NodeJS 程序也可以使用 http 模块来处理 http 请求,从而成为一个基本的 Web 服务器。
回答by hasanga lakdinu
middleware as the name suggests actually middleware is sit between middle.. middle of what? middle of request and response..how request,response,express server sit in express app in this picture you can see requests are coming from client then the express server server serves those requests.. then lets dig deeper.. actually we can divide this whole express server's whole task in to small seperate tasks like in this way. how middleware sit between request and responsesmall chunk of server parts doing some particular task and passed request to next one.. finally doing all the tasks response has been made.. all middle ware can access request object,response object and next function of request response cycle..
中间件顾名思义,实际上中间件位于中间......中间什么?中间的请求和响应..怎么请求,响应Express服务器静坐快递应用在这张照片你可以看到请求从客户端来了那么Express服务器服务器为这些请求..然后让挖更深..其实我们可以把这个以这种方式将整个快递服务器的整个任务分解为小的单独任务。 中间件如何位于请求和响应之间 一小块服务器部分执行某些特定任务并将请求传递给下一个.. 最终完成所有任务 响应已经做出.. 所有中间件都可以访问请求对象、响应对象和请求的下一个函数响应周期..
this is good example for explaining middleware in express youtube video for middleware
这是在中间件的 express youtube 视频中解释中间件的好例子
回答by kmiles
The stupid simple answer
愚蠢的简单答案
Connect and Express are web servers for nodejs. Unlike Apache and IIS, they can both use the same modules, referred to as "middleware".
Connect 和 Express 是 nodejs 的 Web 服务器。与 Apache 和 IIS 不同,它们都可以使用相同的模块,称为“中间件”。

