8

I'm trying to implement the { pushState : true } but it works only for the base route, not with the other that continue to give me error 404.

In Chrome, If I access:

http://example.app/ - OK the console message is displayed

http://example.app/show - error 404 is returned

My route is

    var AppRouter = Backbone.Router.extend({

    routes: {
        '': 'index',
            'show': 'show'
        },

        index: function() {
            console.log('This is the index page');
        },
        show: function() {
            console.log('This is the show page');
        }

    });

    new AppRouter;
    Backbone.history.start({pushState: true});

My .htaccess

<ifModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !index
   RewriteRule (.*) index.html [L]
</ifModule>

What I'm missing or I'm doing wrong?

4

3 回答 3

15

请记住,Backbone 是一个客户端框架——如果您使用基于路径的 URL 进行路由(推送状态),您仍然需要确保服务器为这些 URL 返回正确的标记。因此, Backbone 文档对此进行了总结:

请注意,使用真实 URL 需要您的 Web 服务器能够正确呈现这些页面,因此还需要进行后端更改。例如,如果您有 /documents/100 的路由,如果浏览器直接访问该 URL,则您的 Web 服务器必须能够提供该页面。对于完整的搜索引擎可抓取性,最好让服务器为页面生成完整的 HTML ......但如果它是一个 Web 应用程序,只需呈现与根 URL 相同的内容,然后用 Backbone 填充其余内容视图和 JavaScript 工作正常。

换句话说,如果您的服务器不理解,Backbone 将无法帮助您example.app/show——您必须修复服务器、使用 URL 重写和/或您选择的服务器端语言。

于 2013-03-11T22:15:25.040 回答
0

您需要为这种情况创建一个初始化函数。

我在样板路由器上连接了一些东西,只需在脚本末尾初始化路由器之前将其包含在内。

var initialize = function() {

    var app_router = new AppRouter;

    Backbone.history.start({ pushState: false });

    $(document).on('click', 'a:not([data-bypass])', function(e){

        var href = $(this).prop('href');
        var root = location.protocol + '//' + location.host + '/';

        if (root === href.slice(0, root.length)){
            e.preventDefault();
            Backbone.history.navigate(href.slice(root.length), true);
        }
    });

};
于 2013-09-09T13:11:52.140 回答
-2

我认为您可能只是缺少网址中的“#”。我现在正在关注一些教程,我刚刚意识到他们如何阻止请求进入服务器。

所以不是
http://example.app/show
而是
http://example.app/#/show

和骨干应该能够抓住它。

于 2013-09-24T12:21:21.770 回答