express
是否提供了一种指定中间件始终在链末端运行的方法?
我想创建一对中间件功能,一开始一个,最后一个功能收集了有关调用的分析。
我知道我可以做这样的事情:
app.use(entry);
app.get("/some-endpoint", (req, res, next) => {
res.send("hello").end();
next();
});
app.use(exit);
其中entry()
和exit()
是我的中间件。
但是,关于这个解决方案,我不喜欢两件事。首先,必须调用next()
,否则exit()
中间件将不使用。
另一个是我更希望构建一个可以用作一件零件的Router
。类似:
// MyRouter.js
const router = () => Router()
.use(entry)
.use(exit);
export default router;
// myServer.js
import router from './MyRouter.js';
import express from 'express';
const app = express();
app.use(router());
app.get("/some-endpoint", (req, res) => {
res.send("hello").end();
});
能够将其全部捆绑到总是运行的一件事,这会使它更有用。
由于express包装http.ServerResponse
中的res
对象,您可以在中间件中附加 'finish'
事件的侦听器。然后,当响应"完成"时,exit()
将在事件发射后立即调用。
// analyticMiddleware.js
const analyticMiddleware = (req, res, next) => {
// Execute entry() immediately
// You'll need to change from a middleware to a plain function
entry()
// Register a handler for when the response is finished to call exit()
// Just like entry(), you'll need to modify exit() to be a plain function
res.once('finish', () => exit)
// entry() was called, exit() was registered on the response return next()
return next()
}
module.exports = analyticMiddleware
// myServer.js
import analytics from './analyticMiddleware.js';
import express from 'express';
const app = express();
app.use(analytics);
app.get("/some-endpoint", (req, res) => {
res.send("hello").end();
});