什么是 Node.js? Connect、Express 和“中间件”?

发布于 2024-10-21 11:51:05 字数 95 浏览 3 评论 0原文

尽管我非常了解 JavaScript,但我还是对 Node.js 生态系统中的这三个项目到底做什么感到困惑。是不是像 Rails 的 Rack 之类的东西?有人可以解释一下吗?

Despite knowing JavaScript quite well, I'm confused what exactly these three projects in Node.js ecosystem do. Is it something like Rails' Rack? Can someone please explain?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

最舍不得你 2024-10-28 11:51:05

[更新:自 4.0 版本起,Express 不再使用 Connect。但是,Express 仍然与为 Connect 编写的中间件兼容。我原来的答案如下。]

我很高兴你问到这个问题,因为这绝对是关注 Node.js 的人的一个常见困惑点。这是我最好的解释:

  • Node.js 本身提供了 http 模块,其 createServer 方法返回一个可用于响应 HTTP 请求的对象。该对象继承了 http.Server 原型。

  • Connect 还提供了一个 createServer 方法,该方法返回一个对象继承 http.Server 的扩展版本。 Connect 的扩展主要是为了方便插入中间件。这就是为什么 Connect 将自己描述为“中间件框架”,并且经常被类比为 Ruby 的 Rack。

  • Express 的作用与 Connect 对 http 模块的作用相同:它提供了一个 createServer扩展 Connect 的 Server 原型的方法。因此,Connect 的所有功能都在那里,加上视图渲染和用于描述路线的方便的 DSL。 Ruby 的 Sinatra 是一个很好的类比。

  • 还有其他框架可以进一步扩展 Express!例如,Zappa,它集成了对 CoffeeScript、服务器端 jQuery 和测试的支持。

以下是“中间件”含义的具体示例:开箱即用,以上均不为您提供静态文件。但只需放入 connect.static(Connect 附带的中间件),配置为指向一个目录,您的服务器就会提供对该目录中文件的访问。请注意,Express 还提供 Connect 的中间件; express.staticconnect.static 相同。 (直到最近,两者都被称为staticProvider。)

我的印象是,现在大多数“真正的”Node.js 应用程序都是使用 Express 开发的;它添加的功能非常有用,并且如果您需要,所有较低级别的功能仍然存在。

[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.]

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 itself offers an http module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server prototype.

  • Connect also offers a createServer method, which returns an object that inherits an extended version of http.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.

  • Express does to Connect what Connect does to the http module: It offers a createServer method that extends Connect's Server prototype. So all of the functionality of Connect is there, plus view 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.

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.static is the same as connect.static. (Both were known as staticProvider until recently.)

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.

王权女流氓 2024-10-28 11:51:05

接受的答案确实很旧(现在是错误的)。以下是基于 Connect (3.0) / Express (4.0) 当前版本的信息(带源)。

Node.js 附带的内容

http / https createServer 只需要一个回调(req,res),例如

var server = http.createServer(function (request, response) {

    // respond
    response.write('hello client!');
    response.end();

});

server.listen(3000);

connect 添加的

中间件 基本上是位于应用程序代码和某些低层代码之间的任何软件级别 API。 Connect 扩展了内置 HTTP 服务器功能并添加了插件框架。这些插件充当中间件,因此 connect 是一个中间件框架

它的工作方式非常简单(事实上代码非常短!)。一旦你调用 var connect = require('connect'); var app = connect(); 您将获得一个函数 app,它可以:

  1. 可以处理请求并返回响应。这是因为你基本上得到了这个函数
  2. 有一个成员函数。使用)来管理插件 em> (来自这里因为这一行简单的代码)。

由于 1.),您可以执行以下操作:

var app = connect();

// Register with http
http.createServer(app)
    .listen(3000);

与 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 提供了一个实用程序函数来向 http 注册自身,这样您就不需要调用 <代码>http.createServer(app)。它被称为listen,代码只是创建一个新的http服务器,将连接注册为回调并将参数转发给http.listen来自源代码

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

所以,你可以这样做:

var connect = require('connect');

// Create a connect dispatcher and register with http
var app = connect()
          .listen(3000);
console.log('server running on port 3000');

它仍然是你的旧版本< code>http.createServer 上面有一个插件框架。

ExpressJS添加的

ExpressJS和connect是并行项目。 Connect只是一个中间件框架,具有很好的use功能。 Express 不依赖于 Connect请参阅 package.json)。然而,它完成了 connect 所做的一切,即:

  1. 可以像 connect 一样使用 createServer 注册,因为它也只是一个可以接受 req/res 的函数。代码> 对()。
  2. 使用函数注册中间件
  3. 实用程序listen函数通过http注册自身

除了 connect 提供的功能(表示重复项)之外,它还有更多功能。例如

  1. 具有视图引擎支持
  2. 具有其路由器的顶级动词(get/post等)
  3. 具有应用程序设置支持。

中间件是共享的

ExpressJS 的 use 和 connect 功能是兼容的,因此中间件是共享的。两者都是中间件框架,express 不仅仅是一个简单的中间件框架。

您应该使用哪一个?

我的意见:您已经了解了足够的信息^根据上述内容^做出自己的选择。

  • 如果您要从头开始创建诸如 connect /expressjs 之类的内容,请使用 http.createServer
  • 如果您正在创作中间件、测试协议等,请使用 connect,因为它是 http.createServer 之上的一个很好的抽象。
  • 如果您正在创作网站,请使用 ExpressJS。

大多数人应该只使用 ExpressJS。

接受的答案有什么问题

这些在某个时间点可能是正确的,但现在是错误的:

继承http.Server的扩展版本

错误。它不会扩展它,正如您所看到的......使用它

Express 对 Connect 的作用与 Connect 对 http 模块的作用相同

Express 4.0 甚至不依赖于 connect。 查看当前的 package.json 依赖项部分

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).

What Node.js comes with

http / https createServer which simply takes a callback(req,res) e.g.

var server = http.createServer(function (request, response) {

    // respond
    response.write('hello client!');
    response.end();

});

server.listen(3000);

What connect adds

Middleware is 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

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 app that can:

  1. Can handle a request and return a response. This is because you basically get this function
  2. Has a member function .use (source) to manage plugins (that comes from here because of this simple line of code).

Because of 1.) you can do the following :

var app = connect();

// Register with http
http.createServer(app)
    .listen(3000);

Combine with 2.) and you get:

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 http so that you don't need to make the call to http.createServer(app). Its called listen and the code simply creates a new http server, register's connect as the callback and forwards the arguments to http.listen. From source

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.createServer with a plugin framework on top.

What ExpressJS adds

ExpressJS and connect are parallel projects. Connect is just a middleware framework, with a nice use function. Express does not depend on Connect (see package.json). However it does the everything that connect does i.e:

  1. Can be registered with createServer like connect since it too is just a function that can take a req/res pair (source).
  2. A use function to register middleware.
  3. A utility listen function to register itself with http

In addition to what connect provides (which express duplicates), it has a bunch of more features. e.g.

  1. Has view engine support.
  2. Has top level verbs (get/post etc.) for its router.
  3. Has application settings support.

The middleware is shared

The use function of ExpressJS and connect is compatible and therefore the middleware is shared. Both are middleware frameworks, express just has more than a simple middleware framework.

Which one should you use?

My opinion: you are informed enough ^based on above^ to make your own choice.

  • Use http.createServer if 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.

Most people should just use 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

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 4.0 doesn't even depend on connect. see the current package.json dependencies section

倒带 2024-10-28 11:51:05

Node.js

Node.js 是服务器端的 JavaScript 引擎。
除了所有 js 功能之外,它还包括网络功能(如 HTTP)以及对文件系统的访问。
这与客户端js不同,客户端js的网络任务被浏览器垄断,并且出于安全原因禁止访问文件系统。

Node.js 作为 Web 服务器:表达

在服务器中运行、理解 HTTP 并可以访问文件的东西,听起来像 Web 服务器。但它不是一个。
要使 Node.js 表现得像 Web 服务器一样,必须对其进行编程:处理传入的 HTTP 请求并提供适当的响应。
这就是 Express 的作用:它是用 js 实现的 Web 服务器。
因此,实现一个网站就像配置 Express 路线,并对网站的特定功能进行编程。

中间件和 Connect

Serving 页面涉及许多任务。其中许多任务是众所周知的并且非常常见,因此节点的 Connect 模块(许多可用模块之一)在节点下运行)实现这些任务。
查看当前令人印象深刻的产品:

  • logger 支持自定义格式的请求记录器
  • csrf 跨站点请求伪造保护
  • compress Gzip 压缩中间件
  • basicAuth< /strong> 基本 http 身份验证
  • bodyParser 可扩展请求正文解析器
  • json application/json 解析器
  • urlencoded application/x-www-form-urlencoded 解析器
  • >multipart multipart/form-data 解析器
  • timeout 请求超时
  • cookieParser cookie 解析器
  • session 附带 MemoryStore 的会话管理支持
  • cookieSession 基于 cookie 的会话支持
  • methodOverride 仿 HTTP 方法支持
  • responseTime 计算响应时间并通过 X-Response-Time 公开
  • staticCache 内存static() 中间件的缓存层
  • static 支持 Range 等的流式静态文件服务器
  • directory 目录列表中间件
  • vhost 虚拟主机子域映射中间件
  • favicon 高效的 favicon 服务器(使用默认图标)
  • limit 限制请求正文的字节大小
  • query 自动查询字符串解析器,填充 req.query
  • errorHandler 灵活的错误处理程序

Connect 是一个框架,通过它您可以选择您需要的(子)模块。
Contrib Middleware 页面列举了一长串附加中间件
Express 本身附带最常见的 Connect 中间件。

该怎么办?

安装node.js。
Node 附带了npm,即节点包管理器
命令npm install -g express将全局下载并安装express(查看express指南).
在命令行(而不是在节点中)运行 express foo 将创建一个名为 foo 的可立即运行的应用程序。切换到它的(新创建的)目录并使用命令 node 运行它,然后打开 http://localhost:3000 并查看。
现在你进来了。

node.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 as a web server: 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.

Middleware and Connect

Serving pages involves a number of tasks. Many of those tasks are well known and very common, so node's Connect module (one of the many modules available to run under node) implements those tasks.
See the current impressing offering:

  • logger request logger with custom format support
  • csrf Cross-site request forgery protection
  • compress Gzip compression middleware
  • basicAuth basic http authentication
  • bodyParser extensible request body parser
  • json application/json parser
  • urlencoded application/x-www-form-urlencoded parser
  • multipart multipart/form-data parser
  • timeout request timeouts
  • cookieParser cookie parser
  • session session management support with bundled MemoryStore
  • cookieSession cookie-based session support
  • methodOverride faux HTTP method support
  • responseTime calculates response-time and exposes via X-Response-Time
  • staticCache memory cache layer for the static() middleware
  • static streaming static file server supporting Range and more
  • directory directory listing middleware
  • vhost virtual host sub-domain mapping middleware
  • favicon efficient favicon server (with default icon)
  • limit limit the bytesize of request bodies
  • query automatic querystring parser, populating req.query
  • errorHandler flexible error handler

Connect is the framework and through it you can pick the (sub)modules you need.
The Contrib Middleware page enumerates a long list of additional middlewares.
Express itself comes with the most common Connect middlewares.

What to do?

Install node.js.
Node comes with npm, the node package manager.
The command npm install -g express will download and install express globally (check the express guide).
Running express foo in 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:3000 and see.
Now you are in.

所有深爱都是秘密 2024-10-28 11:51:05

Connect 为会话管理、身份验证、日志记录等常见 HTTP 服务器功能提供“更高级别”的 API。 Express 建立在 Connect 之上,具有高级(类似 Sinatra)功能。

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.

满意归宿 2024-10-28 11:51:05

Node.js 本身提供了一个 HTTP 模块,其 createServer 方法返回一个可用于响应 HTTP 请求的对象。该对象继承 http.Server 原型。

Node.js itself offers an HTTP module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server prototype.

留蓝 2024-10-28 11:51:05

相关信息,尤其是当您使用 NTVS 来处理 Visual Studio IDE 时。 NTVS 在 Visual Studio 2012、2013 中添加了 NodeJS 和 Express 工具、脚手架、项目模板。

此外,将 ExpressJS 或 Connect 称为“WebServer”的用语也不正确。您可以使用或不使用它们来创建基本的 Web 服务器。一个基本的NodeJS程序也可以使用http模块来处理http请求,从而成为一个基本的Web服务器。

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.

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.

汐鸠 2024-10-28 11:51:05

中间件顾名思义,实际上中间件位于中间..中间是什么?请求和响应的中间..请求、响应、Express 服务器如何位于 Express 应用程序中
在这张图中,您可以看到请求来自客户端,然后 Express 服务器服务这些请求。然后让我们更深入地挖掘。实际上,我们可以将整个 Express 服务器的整个任务分成小的单独任务,就像这样。
中间件如何位于请求和响应之间一小块服务器部件执行某些特定任务并将请求传递给下一篇..终于完成了所有任务的响应..
所有中间件都可以访问请求对象、响应对象和请求响应周期的下一个函数。

这是解释 Express 中的中间件的好例子 中间件的 YouTube 视频

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 response small 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..

this is good example for explaining middleware in express youtube video for middleware

一直在等你来 2024-10-28 11:51:05

中间件是在传入的请求之间或中间运行的特殊功能。从我们的 api 发出的响应。
例如我们使用
app.use((req, res, next)=>{ }

这里 next 作为 Express js 中 req 和 res 之间的中间件

Middleware are special functions that run between or in the middle of request comming in & response going out from our api.
For example we use
app.use((req, res, next)=>{ }

here next work as a middleware between req and res in express js

梦晓ヶ微光ヅ倾城 2024-10-28 11:51:05

愚蠢的简单答案

Connect 和 Express 是 Nodejs 的 Web 服务器。与 Apache 和 IIS 不同,它们都可以使用相同的模块,称为“中间件”。

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".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文