10

我有一个奇怪的问题,我还没有弄清楚。这很简单,这可能就是我遇到问题的原因:)

首先,这是路由表...

routes: {
    '': 'root', //called
    'report': 'report', // called
    'report/add': 'reportAdd', // not called
    'report/print': 'reportPrint', // not called
    'report/settings': 'reportSettings', // not called
},

您会看到我标记了哪些有效,哪些无效。问题归结为所有子路由(即report/add)不匹配。

骨干历史在 main.js 中被正确调用,如下所示:

app.Router = new Router();
Backbone.history.start({ pushState: true });

显然,这是在正确的位置,因为路线正在工作,而不是子路线。我已经尝试了所有root选项Backbone.history和沉默,parameter但没有任何运气。

我想这是一个配置/设置问题,但我找不到任何答案。我究竟做错了什么?任何帮助深表感谢。

顺便说一句,我正在使用 requirejs 和 Backbone Boilerplate,但我不知道这会有什么不同。

更新:虽然提供的答案在技术上是正确的,但问题出在 Backbone Boilerplate 上。有关说明,请参阅此博客文章的底部。我和那里的第一个评论者有同样的问题。

4

1 回答 1

10

正如评论中所讨论的,问题在于,当使用推送状态样式的 URL 时,服务器无法识别主干路由 URL。

举例来说,假设您的应用程序的根位于server/app/index.html,并且您正在尝试使用 Backbone 路由到的 URL /report/print。使用 URL片段路由,这很好:

http://server/app/index.html#report/print

服务端忽略后面的部分#,返回index.html;然后加载 Backbone 路由到report/print.

但如果您使用的是push-state routing,那么 URL 如下所示:

http://server/app/index.html/report/print

服务器会抛出 404 错误,因为它无法识别该路径上的任何内容,因此甚至永远不会加载 Backbone。


解决方案是:

  1. 正如Backbone.js 文档所述,修改服务器代码,以便服务器为每个 Backbone 路由呈现正确的内容,或者
  2. (我认为这更容易)在 Web 服务器(IISApache)上进行 URL 重写,以便它将返回index.html任何像 , 等主干路由的index.html/report/print请求index.html/report/add

例如,在 IIS 中,您可以将以下内容放在应用程序根目录下的 web.config 中:

<rewriteMaps>
    <rewriteMap name="StaticRewrites">
        <add key="index.html/report/print" value="index.html" />
        <add key="index.html/report/add" value="index.html" />
        <!-- etc -->
    </rewriteMap>
</rewriteMaps>
于 2012-12-10T17:20:43.490 回答