【问题标题】:Node.js:Route precedence and ordering (sails.js)Node.js:路由优先级和排序(sails.js)
【发布时间】:2017-09-29 18:53:20
【问题描述】:

在我的sails.js 应用程序中,我有两条这样的路线:

    '/': {controller:'HomeController',action:'home'},

   'GET /:category/:subcategory/:keyword':{controller:'SearchController',action:'index'

当我运行默认路由 (/) 时,它将始终执行此路由 GET /:category/:subcategory/:keyword.

为什么会这样??

路由文件中路由的顺序是

1)/

2)GET /:category/:subcategory/:keyword

【问题讨论】:

  • GET /:category/:subcategory/:keyword 有点像GET /*/*/* 所以它可能匹配你的/.. 如果你在GET /:category... 中不匹配的路由上调用next,你可以颠倒顺序首先检查它。
  • 所以我需要将GET /:category/:subcategory/:keyword 路线放在首位??
  • 实际上,不.. 我认为这没有意义.. 呃.. 我没有真正使用过sails.js.. 但我感觉你可能想要GET / in第一条路线。
  • 现在GET / 排在第一位
  • 它给你主页,但也访问 SearchController 路由?如果是这样,我敢打赌,您主页上的某些资源会意外匹配该路线。例如,如果您有一个带有src="/images/icons/smiley.png" 的图像,那将匹配您的/:category/:subcategory/:keyword 路由。脚本和其他资源类似。

标签: javascript node.js express sails.js


【解决方案1】:

正如上面评论中提到的,您的一般路线 /:category/:subcategory/:keyword 被击中,因为它必须与您主页上的资产网址匹配。此路由将匹配任何三部分路径,例如:

  • /images/icons/smiley.png
  • /scripts/thirdparty/jquery.min.js

等等!

有两种方法可以解决此问题。一种方法是让您的SearchController 网址更加具体。也许/search/:category/:subcategory/:keyword 是个好主意?这是最简单的,应该立即清除与您的资产的任何冲突。


但是如果你真的需要catch-all路由会干扰其他特定的路由,那么解决方案就是先catch特定的路由。例如在routes.js:

'GET /images/*': 'RouteController.showAsset',
'GET /scripts/*': 'RouteController.showAsset',
'GET /styles/*': 'RouteController.showAsset',
//...
'GET /:category/:subcategory/:keyword': 'SearchController.index',

然后用方法创建一个控制器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/robots.txt/favicon.ico 等冲突的/:userName 路由时,我发现这种方法是值得的。但是,它需要维护,因此,如果您认为第一种方法对您有用,我会使用它。

【讨论】:

  • 让我试试你的答案
猜你喜欢
  • 2013-07-18
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 2016-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多