How to use HTML5 pushState in Backbone.js correctly?

I am using coenraets Employee Directory as a starting point for my Backbone application. The first thing I would like to do is change the routing to use HTML5 PushState instead of hash hash bang tags.

First I changed:

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

Then:

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

Now, if you go to localhost:8000/contacts instead of localhost:8000/#/contacts , it will give a 404 error, regardless of whether you clicked on Navbar or manually typed the URL.

Am I doing something wrong? Thanks.

UPDATE I added this code and now it works fine when I click the [stateful] link. But if I refresh the page while I am in localhost:8000/contacts , I still get the 404 error [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); } }); 

Update 2

In addition to the above code, I added the following route in my Express.js application. If you look closely, you will notice that the URL string changes from localhost:3000/#contact to localhost:3000/contact , although this happens quite quickly. There may be a better way to do this, but I am happy with this approach for a while.

 app.get('/contact', function(req, res) { res.redirect('/#contact'); }); 
+4
source share
2 answers

Suppose you have only one html file. You need to use something similar for all of your routes displaying the same html file:

 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()); }); }); 

I do not know if it is useful to you. That was for me.

+2
source

No, this may not be the best way in your update 2.

Since what we do is a single page application, so we just need to:

Server version:
For a query, for example: http://yourdomain.com/whatever , you simply return the index page.

Frond end:
Nothing. The backbone will process it automatically, it will change the URL http://yourdomain.com/whatever automatically to http://yourdomain.com/#whatever . And since we use {pushstate: true} , Backbone will change it to http://yourdomain.com/whatever for the user to view. All this will be done transparently.
(All you need to do at the second end is to remove the # in your url link.)

0
source

Source: https://habr.com/ru/post/1484861/


All Articles