如何拦截node.js表达请求

时间:2021-02-28 16:58:49

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.

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

1 个解决方案

#1


40  

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添加到中间件链,这可能会使其超出用户定义的中间件。

#1


40  

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添加到中间件链,这可能会使其超出用户定义的中间件。