简体   繁体   中英

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:

// 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.

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.

How can i resolve this conflict? Thanks.

Are you using next() in one of the handlers?

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.

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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