如何拦截node.js表示请求
快递中,我定义了一些路线
app.post("/api/v1/client", Client.create); app.get("/api/v1/client", Client.get); ...
我已经定义了如何处理客户端控制器中的请求。 有没有办法,我可以做一些预处理请求,然后在我的控制器中处理它们? 我特别想要检查API调用者是否有权访问路由,使用访问级别的概念。 任何意见,将不胜感激。
你可以通过几种方法来做你所需要的。
这将放置一个中间件,将用于击中路由器之前。 确保路由器之后添加了app.use()
。 中间件的顺序很重要。
app.use(function(req, res, next) { // Put some preprocessing here. next(); }); app.use(app.router);
您也可以使用路由中间件。
var someFunction = function(req, res, next) { // Put the preprocessing here. next(); }; app.post("/api/v1/client", someFunction, Client.create);
这将为该路线做一个预处理步骤。
注意:确保你的app.use()
调用在你的路由定义之前。 定义路由会自动将app.router添加到中间件链,这可能会使其位于用户定义的中间件之前。