Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 指定始终在末尾运行的Express中间件?_Node.js_Express - Fatal编程技术网

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();
});