如何拦截node.js的前preSS要求 [英] How to intercept node.js express request

查看:153
本文介绍了如何拦截node.js的前preSS要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在EX preSS,我已经定义了一些路线

In express, I have defined some routes

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

我已经定义如何处理客户端控制器内部的请求。有没有一种方法,我可以做一些pre-处理的要求,在我的控制器处理以前?我特别希望,以检查API调用者被授权访问路径使用访问级别的概念。任何意见将是AP preciated。

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.

推荐答案

您可以做你在几个方面需要什么。

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

这将会把会击中路由器之前使用的中间件。确保与添加路由器app.use()之后。中间件顺序很重要。

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 someFucntion = function(req, res, next) {
  // Put the preprocessing here.
  next();
};
app.post("/api/v1/client", someFucntion, Client.create);

这会为这条路一preprocessing一步。

This will do a preprocessing step for that route.

请注意:你的路由定义之前,请确保您的 app.use()调用的。定义路由自动添加app.router到中间件链,这可以把它前面的用户定义的中间件。

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.

这篇关于如何拦截node.js的前preSS要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆