【问题标题】:How to properly use HTML5 pushState in Backbone.js?如何在 Backbone.js 中正确使用 HTML5 pushState?
【发布时间】:2013-06-06 15:36:21
【问题描述】:

我使用 coenraets 的 Employee Directory 作为我的 Backbone 应用程序的起点。我想做的第一件事是更改路由以使用 HTML5 PushState 而不是 hash-hash bang-bangs。

首先我改变了:

<ul class="nav">
  <li class="active"><a href="/">Home</a></li>
  <li><a href="/contact">Contact</a></li>
</ul>

那么:

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

现在,如果您转到 localhost:8000/contacts 而不是 localhost:8000/#/contacts,则无论您是单击导航栏还是手动输入 URL,都会出现 404 错误。

我做错了吗?谢谢。

更新:我添加了这段代码,当我点击一个链接[stateful]时它现在可以正常工作了。但是如果我在localhost:8000/contacts 中刷新页面,我仍然会收到 404 错误 [stateless]

$(document).on('click', 'a:not([data-bypass])', function(e){
  href = $(this).prop('href')
  root = location.protocol+'//'+location.host+'/'
  if (root===href.slice(0,root.length)){
    e.preventDefault();
    Backbone.history.navigate(href.slice(root.length), true);
  }
});

更新 2

除了上述代码之外,我还在我的 Express.js 应用程序中添加了以下路由。如果您仔细观察,您会注意到 URL 栏从 localhost:3000/#contact 变为 localhost:3000/contact,尽管它发生得非常快。也许有更好的方法来做这件事,但我暂时对这种方法感到满意。

app.get('/contact', function(req, res) {
  res.redirect('/#contact');
});

【问题讨论】:

标签: backbone.js pushstate


【解决方案1】:

假设您只有一个 html 文件。您需要为所有路线使用类似的东西显示相同的 html 文件:

app.configure(function () {

  // static files
  app.use(express.static(__dirname + '/public'));

  // default html file (with any request)
  app.use(function (req, res) {
    var contents = fs.readFileSync(__dirname + '/public/index.html');
    res.send(contents.toString());
  });

});

不知道对你有没有用。这是给我的。

【讨论】:

    【解决方案2】:

    不,这可能不是更新 2 中的最佳方式。

    既然我们做的是单页应用,那么我们需要做的只是:

    服务器端:
    对于像:http://yourdomain.com/whatever 这样的请求,您只需返回 index 页面。

    前端:
    没有。 Backbone 会自动处理它,它会自动将 url http://yourdomain.com/whatever 更改为 http://yourdomain.com/#whatever。由于我们使用{pushstate: true},Backbone 会将其更改为http://yourdomain.com/whatever 供用户查看。所有这些都将透明地完成。
    (您需要在前端做的就是删除# 链接中的url。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-31
      • 2012-10-07
      • 2012-06-21
      • 2019-02-08
      相关资源
      最近更新 更多