Backbone router: Use hashbangs

2019-09-07 01:04发布

问题:

I was setting up a simple router in Backbone.js while I noted an issue, I googled for a long time and found some solutions.

The problem is that whenever I navigate to a url, this url will work while I'm inside the app itself, but once you bookmark it and return it will obviously return a 404 since that page doesn't exist.

Backbone.history.navigate('test', true);

This will navigate to http://www.domain.com/test, which is great, but once you refresh the same URL it returns a 404.

There are ways to get this to work with using a specific .htaccess file, but I'm building this inside an existing website, so I can't use this.

Is there a way in Backbone.js to revert to just using hashbangs? My url would then look like this `http://www.domain.com/#!/test This might not be the cleanest URL, but at least it will work.

Or am I just missing something obvious here? It can't be that I'm the only person with this problem.

回答1:

You're using pushState according to your url, so you've got 2 main options:

  • stop using pushState when starting Backbone history (which would be the equivalent of using a hashbang, except for SEO)
  • have your server return a page for every URL your app generates (it can be the same exact page)

In the second case, if you don't care about SEO, you can have a catch all rule always returning (e.g.) index.html containing your Backbone app. When you start Backbone's history, it will lokk at the URL and navigate to the proper page (although you might have a "double render" effect).

If you're worried about SEO, you need to return page content for SEO along with your Backbone app.