How to intercept node.js express request

点点圈 提交于 2019-11-29 05:50:57

问题


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.


回答1:


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(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.



来源:https://stackoverflow.com/questions/11038830/how-to-intercept-node-js-express-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!