node.js - Nodejs Express 通配符路由不起作用

标签 node.js express wildcard

我正在用express作为路由器在nodejs中做一个API。

现在我正在尝试实现一个 client-id 和一个 apikey 来为 API 添加一些安全性,我面临的问题是下一个:

我的一个 API 调用是这样的: router.get("roles/get-objects/:mail/:filter*?") 所以这意味着,我可以请求这样的对象: /roles/get-objects/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a575b53567a575b535614595557" rel="noreferrer noopener nofollow">[email protected]</a>/customer

现在棘手的部分开始了...当我需要建立一个中间件来读取客户端 ID 和 apikey 来验证客户端是否有权使用 API 时,所以我这样做了:

在中间件的声明中,我使用了这个通配符: router.all('/*', function (req, res, next) { XXXX})

问题是,我在中间件中尝试过,作为通配符一切...... 我希望任何 API 调用都通过该中间件进行过滤,但显然我找不到合适的通配符......

当我使用/roles/* 作为通配符时,如果我向 /roles 发出请求它确实有效,但是当我使用完整的 URL 时,例如: /roles/get-objects/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="38555951547855595154165b5755" rel="noreferrer noopener nofollow">[email protected]</a>/customer它不会通过我的中间件。

那么有人有什么想法吗?我开始失去理智

非常感谢大家!

编辑: 现在我正在使用这个中间件声明: router.use(function (req, res, next) {XXXX})

所以当我打电话时: /roles/get-objects/

它已执行,问题是当我将电子邮件添加到路由时: /roles/get-objects/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ae7ebe3e6cae7ebe3e6a4e9e5e7" rel="noreferrer noopener nofollow">[email protected]</a>

该应用程序直接进入我所拥有的路线,但省略了我的中间件: router.get("角色/get-objects/:mail",

我不明白为什么会发生这种情况,显然一切都应该首先通过我的中间件,还是我错了?

最佳答案

如果您想建立一个中间件来检查所有 URL 以 /roles/ 开头的 HTTP 请求,则该中间件应放置在任何其他特定路由器定义之前:

router.use('/roles', function(req, res, next) {...});
...
router.get('/roles/get-objects/:mail', ...);

如果中间件定义在特定路由之后,当HTTP请求到来时,会针对特定路由进行处理,中间件将不再被执行:

router.get('/roles/get-objects/:mail', ...);
...
router.use('/roles', function(req, res, next) {...}); // This middleware logic won't execute when request is sent to '/roles/get-objects/some-email', as the request has already been handled and response is already sent to browser.

关于node.js - Nodejs Express 通配符路由不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44900100/

相关文章:

node.js - 无法理解使用 Node.js 的 Express 服务器概念

search - Solr 中的通配符搜索

makefile - 使用多个通配符进行过滤

mysql - 如何在 Sequelize 中正确设置自定义 'through' 表?

angularjs - 如何在没有 Node 的情况下本地运行 Angular 2 应用程序

node.js - 从 Google Apps 脚本中的 https 调用获取状态文本

javascript - 将参数从中间件传递到 express 路由器

database - node.js 传递变量

node.js - 403 禁止在 Node.js 中使用 sendgrid 发送电子邮件

java - Log4j2 通配符记录器名称