[英]Conflicts between endpoints in Node.js with express application
首先,我已经搜索了这个问题的解决方案,我没有找到任何东西。 对不起,如果它是重复的。
我在express + node.js app中有两个端点,如下所示:
// Gets a tweet by unique id
app.get('/tweets:id', function(req, res, next) {
// Response management
});
// Gets mentions of user unique id
app.get('/tweets/mentions', function(req, res, next) {
// Response management
});
问题是请求GET申请“/ tweets / mentions” ,首先是“/ tweets /:id” ,后来是“/ tweets / mentions” ,这引起了冲突。
我试图更改端点的声明顺序,但两个端点始终都有请求。
我也试过像“/ tweets :: mentions”这样的东西,但我需要通过“/ tweets / mentions”访问端点,我想有一种可能的方法。
我该如何解决这个冲突? 谢谢。
你在其中一个处理程序中使用next()
吗?
next()
将控制传递给下一个匹配的路由,因此在您的示例中,如果其中一个被调用并且在其中调用next()
,则将调用另一个。
如果你有多个基本路径,我总是建议使用'路由器',因为它可以帮助你保持井井有条。
您可以通过检查“tweet by id”处理程序中的req.params.id
的值来解决冲突。
对于具有附加参数的路由,建议不要使用与其他路由相同的基本路径。
类似的东西可以为你工作:
app.get('/tweets/users/:id', function(req, res, next) {
// Response management
});
// Gets mentions of user unique id
app.get('/tweets/mentions', function(req, res, next) {
// Response management
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.