编辑:这篇文章是为 Express 3 写的。从那时起,小细节发生了变化,但在概念上是相同的。
开始之前的注意事项:Express 构建在 Connect 之上,它基本上处理了它的中间件。当我在这些示例中写express 时,我同样可以轻松地写connect。
在底层,你有 Node 的 HTTP 服务器模块。它看起来像这样:
var http = require("http");
http.createServer(function(request, response) {
response.end("Hello world!\n");
}).listen(1337, "localhost");
基本上,您创建一个处理所有 HTTP 请求的单个 函数。尝试运行上述代码并访问 localhost:1337/hello 或 localhost:1337/wow-anime。从技术上讲,这就是你真正需要的!
但是假设您希望许多函数每次都运行。也许你想添加一个命令行记录器,也许你想让每个请求都变成纯文本。
var http = require("http");
http.createServer(function(request, response) {
// logger
console.log("In comes a " + request.method + " to " + request.url);
// plain text
response.writeHead(200, { "Content-Type": "text/plain" });
// send response
response.end("Hello world!\n");
}).listen(1337, "localhost");
在 Express/Connect 中,您可以改为这样写:
var express = require("express");
var app = express();
app.use(express.logger());
app.use(function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
next();
});
app.use(function(request, response) {
response.end("Hello world!\n");
});
app.listen(1337);
我认为中间件是一个函数列表。当一个 HTTP 请求进来时,我们从顶部开始,从上到下遍历每个中间件,并在调用 response.end(或 Express 中的 response.send)时停止。
如果你有兴趣,我写了更详细的a blog post that explains Express and middleware。