简体   繁体   中英

Why is Express.js routing not selecting correct route?

So I have the following route:

app.delete('/project/:id', crud.deleteProject);
app.delete('/project/resource/', crud.removeResourceFromProject);

When I run the ajax call with the url http://mysite.no/project/resource/ :

delete: function(url,data) {
return $.ajax({
  url: url,
  type: "DELETE",
  dataType: 'json',
  data: data
});

Express runs the crud.deleteProject function.

If I comment out or move it below the other route, it works as expected.

Why is this?

In Express, the order of your routing definitions is important. It will perform the first matching route. As Blex states, '/:id' is a wildcard value and is matching '/resource' instead of skipping past and following the correct route definition.

A solution is to switch the definitions to have '/project/resource' defined before '/project/:id'

A solution is to add another path layer eg '/project/res/resource' instead of '/project/resource' as Express will not match this to '/:id' .

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