Node.js 指定始终在末尾运行的Express中间件?
Node.js 指定始终在末尾运行的Express中间件?,node.js,express,Node.js,Express,express是否提供了一种方法来指定中间件始终在链的末端运行 我想创建一对中间件函数,一个在开始,一个在结束,它们收集关于调用的分析 我知道我可以做这样的事情: app.use(entry); app.get("/some-endpoint", (req, res, next) => { res.send("hello").end(); next(); }); app.use(exit); 其中entry()和exit()是我的中间件 然而,这个解决方案有两件事我不喜欢。首
express
是否提供了一种方法来指定中间件始终在链的末端运行
我想创建一对中间件函数,一个在开始,一个在结束,它们收集关于调用的分析
我知道我可以做这样的事情:
app.use(entry);
app.get("/some-endpoint", (req, res, next) => {
res.send("hello").end();
next();
});
app.use(exit);
其中entry()
和exit()
是我的中间件
然而,这个解决方案有两件事我不喜欢。首先,必须调用next()
,否则将不使用exit()
中间件
另一个是,我更愿意构建一个路由器
,它可以作为一个整体使用,只需工作即可。比如:
// 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 wrapps中的
res
对象http.ServerResponse
,您可以在中间件中为附加侦听器。然后,当响应“完成”时,一旦触发事件,就会调用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
谢谢虽然我保留了
entry()
和exit()
中间件函数,并如上所述将它们与Router()
链接在一起,主要是为了代码的清洁。从功能上来说,它和你给的是一样的。
// 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();
});