带有参数的 Express 中间件会扰乱其他路由

问题描述 投票:0回答:1

问题是当我在带有参数的路径上定义中间件时,中间件也适用于没有参数的其他路由

我有这个代码:

app.use('/group/:groupId', groupmiddleware)

//这个路由应该经过groupMiddleware app.get('/groups/:groupId/another', (req, res) => {});

// 不应该经过groupMiddleware的路由 app.get('/groups/all', (req, res) => {});

现在,当我向 /groups/all 发送请求时,它不应该通过中间件 任何建议或修复方法将不胜感激。 我用的是express 4.18

node.js express
1个回答
0
投票

这完全取决于您定义路线的方式。您可以像这样定义中间件,因此它将在该特定路由上使用。

假设如果您只想在这条路由上使用该中间件,那么请执行以下操作:

app.get('/groups/:groupId/another', [groupmiddleware], (req, res) => {})

所以

groupmiddleware
只会在这条路线上使用。

路线的顺序也取决于express,按此顺序定义路线:

app.get('/groups/all', (req, res) => {})
app.get('/groups/:groupId', (req, res) => {})
app.get('/groups/:groupId/another', (req, res) => {})
© www.soinside.com 2019 - 2024. All rights reserved.