中间件堆栈
基本中间件是一个需要 3 个参数请求,响应和下一个的函数。
然后通过 app.use
,将一个中间件安装到 Express App 中间件堆栈。在每个中间件中操作请求和响应,然后通过 next()
的调用将其传送到下一个中间件。
例如,以下代码:
var express = require('express');
var app = express();
app.use((request, response, next) => {
request.propA = "blah blah";
next();
});
app.use('/special-path', (request, response, next) => {
request.propB = request.propA + " blah";
if (request.propB === "blah blah blah")
next();
else
response.end('invalid');
});
app.use((request, response, next) => {
response.end(request.propB);
});
app.listen(1337);
大致可以翻译成:
var http = require('http');
http.createServer((request, response) => {
//Middleware 1
if (isMatch(request.url, '*')) {
request.propA = "blah blah";
}
//Middleware 2
if (isMatch(request.url, "/special-path")) {
request.propB = request.propA + " blah";
if (request.propB !== "blah blah blah")
return response.end('invalid');
}
//Middleware 3
if (isMatch(request.url, "*")) {
return response.end(request.propB);
}
});
server.listen(1337);