如何使用express在所有请求之前和之后调用函数

sle*_*rou 2 node.js express

我在节点中有使用express的rest api。

我有一些终点...

router.get('/admin/logs', (req, res) => {
Run Code Online (Sandbox Code Playgroud)

我想在调用所有端点时调用特定函数。

我怎样才能做到这一点?

因此,简单的方法是将函数调用放入每个请求中。

但有什么全球性的方法吗?

感谢您的任何帮助。

小智 8

您根本不需要使用任何第三方 NPM。您可以创建一个将在每次 API 调用后执行的中间件。 注意:您还可以在此处获取以前的 req 对象,以便您可以访问类似 -> req.user 的内容。

app.use((req, res, next) => {
res.on('finish', async () => {
// You might have to add a logic here like if(req.user) then perform following things
// Do whatever you want to do here after every API call finishes
// you can access res.statusCode, req.method etc.
});
next();
});
Run Code Online (Sandbox Code Playgroud)