简体   繁体   English

为什么Express.js路由未选择正确的路由?

[英]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/ : 当我使用URL http://mysite.no/project/resource/运行ajax调用时:

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

Express runs the crud.deleteProject function. Express运行crud.deleteProject函数。

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. 在Express中,路由定义的顺序很重要。 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. 如Blex所述, '/:id'是通配符值,并且与'/resource'匹配,而不是跳过并遵循正确的路由定义。

A solution is to switch the definitions to have '/project/resource' defined before '/project/:id' 一种解决方案是将定义切换为在'/project/:id'之前定义'/project/resource' '/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' . 一种解决方案是添加另一个路径层,例如'/project/res/resource'而不是'/project/resource'因为Express不会将此匹配到'/:id'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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