Node.js:路由优先和sorting(sails.js)
在我的sails.js
应用程序中,我有两个这样的路线:
'/': {controller:'HomeController',action:'home'}, 'GET /:category/:subcategory/:keyword':{controller:'SearchController',action:'index'
当我运行默认路由( /
)时,它将始终执行此路由GET /:category/:subcategory/:keyword
。
为什么会这样?
路由文件中的路由顺序是
1) /
2) GET /:category/:subcategory/:keyword
正如在上面的评论中提到的,你的非常普遍的路线/:category/:subcategory/:keyword
被击中,因为它必须匹配你的主页上的资源URL。 这条路线将匹配任何三部分path,例如:
-
/images/icons/smiley.png
-
/scripts/thirdparty/jquery.min.js
等等!
将有两种方法来解决这个问题。 一个会让你的SearchController
更具体的url。 也许/search/:category/:subcategory/:keyword
将是一个好主意? 这是最简单的,应该立即清理与您的资产的任何冲突。
但是,如果你真的需要所有可能干扰其他特定路线的路线,那么解决办法就是首先捕捉特定的路线。 例如,在routes.js
:
'GET /images/*': 'RouteController.showAsset', 'GET /scripts/*': 'RouteController.showAsset', 'GET /styles/*': 'RouteController.showAsset', //... 'GET /:category/:subcategory/:keyword': 'SearchController.index',
然后用下面的方法创build一个控制器RouteController
:
showAsset: function(req, res) { var pathToAsset = require('path').resolve('.tmp/public', req.path); // ex should be '.tmp/public/images/icons/smiley.png' return res.sendfile(pathToAsset); },
你可能需要添加一些东西来检查文件的存在,但这是主意。
当我想要一个不会与我的/contact
, /about
, /about
/favicon.ico
, /about
/favicon.ico
等冲突的/:userName
路由时,我发现这种方法是值得的。但是,它需要工作来维护,所以如果你认为第一种方法可以为你工作,我会用这个。