如何拦截node.js表达请求 [英] How to intercept node.js express request

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

问题描述

在表达中,我已经定义了一些路由。

In express, I have defined some routes

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

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

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

注意:确保您的 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表达请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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