如何拦截 node.js 快递请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11038830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:52:30  来源:igfitidea点击:

How to intercept node.js express request

apinode.jsexpressintercept

提问by Ryan Olds

In express, I have defined some routes

在快递中,我定义了一些路线

app.post("/api/v1/client", Client.create);
app.get("/api/v1/client", Client.get);
...

I have defined how to handle requests inside a Client controller. Is there a way that I can do some pre-processing to the requests, before handling them in my controller? I specifically want to check if the API caller is authorized to access the route, using the notion of access levels. Any advice would be appreciated.

我已经定义了如何处理客户端控制器内的请求。在我的控制器中处理请求之前,有没有办法对请求进行一些预处理?我特别想使用访问级别的概念检查 API 调用者是否有权访问路由。任何意见,将不胜感激。

回答by Ryan Olds

You can do what you need in a couple of ways.

您可以通过多种方式完成所需的操作。

This will place a middleware that will be used before hitting the router. Make sure the router is added with app.use()after. Middleware order is important.

这将放置一个将在访问路由器之前使用的中间件。确保路由器添加app.use()后。中间件顺序很重要。

app.use(function(req, res, next) {
  // Put some preprocessing here.
  next();
});
app.use(app.router);

You can also use a route middleware.

您还可以使用路由中间件。

var someFunction = function(req, res, next) {
  // Put the preprocessing here.
  next();
};
app.post("/api/v1/client", someFunction, Client.create);

This will do a preprocessing step for that route.

这将为该路线执行预处理步骤。

Note: Make sure your app.use()invokes are before your route definitions. Defining a route automatically adds app.router to the middleware chain, which may put it ahead of the user defined middleware.

注意:确保您的app.use()调用位于路由定义之前。定义路由会自动将 app.router 添加到中间件链中,这可能会将其置于用户定义的中间件之前。