简体   繁体   English

Node.js中端点与明确应用程序之间的冲突

[英]Conflicts between endpoints in Node.js with express application

First of all, i have searched the solution to this problem and i didn't found anything. 首先,我已经搜索了这个问题的解决方案,我没有找到任何东西。 Sorry if it's duplicated. 对不起,如果它是重复的。

I have in my express+node.js app two endpoints like this: 我在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
});

The problem is that requesting a GET petition to "/tweets/mentions" , is attended first by "/tweets/:id" and later by "/tweets/mentions" , making a conflict. 问题是请求GET申请“/ tweets / mentions” ,首先是“/ tweets /:id” ,后来是“/ tweets / mentions” ,这引起了冲突。

I have tried to change the declaration order of the endpoints, but always the request is attended by both endpoints. 我试图更改端点的声明顺序,但两个端点始终都有请求。

Also I have tried things like "/tweets::mentions" , but I need to access the endpoint via "/tweets/mentions" , and I suppose there is a possible way. 我也试过像“/ tweets :: mentions”这样的东西,但我需要通过“/ tweets / mentions”访问端点,我想有一种可能的方法。

How can i resolve this conflict? 我该如何解决这个冲突? Thanks. 谢谢。

Are you using next() in one of the handlers? 你在其中一个处理程序中使用next()吗?

next() passes control to the next matching route, so in your example, if one of them is called and inside it you call next() , the other one will be called. next()将控制传递给下一个匹配的路由,因此在您的示例中,如果其中一个被调用并且在其中调用next() ,则将调用另一个。

I allways recommend to use 'Router' if you have more than one base path because it helps you to keep it organized. 如果你有多个基本路径,我总是建议使用'路由器',因为它可以帮助你保持井井有条。

您可以通过检查“tweet by id”处理程序中的req.params.id的值来解决冲突。

For routes with additional parameters is always recommended to not use the same base path of other routes. 对于具有附加参数的路由,建议不要使用与其他路由相同的基本路径。

Something like could work for you: 类似的东西可以为你工作:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM