中介軟體堆疊
基本中介軟體是一個需要 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);