指定总是在最后运行的Express中间件?

express是否提供了一种方法来指定中间件始终在链的末端运行?

我想创build一对中间件function,一个在开始,一个在最后,收集关于这个调用的分析。

我知道我可以做这样的事情:

 app.use(entry); app.get("/some-endpoint", (req, res, next) => { res.send("hello").end(); next(); }); app.use(exit); 

entry()exit()是我的中间件。

不过,有两件事我不喜欢这个解决scheme。 首先, next()必须被调用,否则exit()中间件将不会被使用。

另一个是,我宁愿build立一个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中的res对象包装了http.ServerResponse ,因此可以在中间件中附加'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(); });