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

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

问题描述

在express中,我定义了一些路由

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天全站免登陆