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'); });
source share