I am using coenraets' Employee Directory as a starting point for my Backbone application. The first thing I would like to do is to change routing to use the HTML5 PushState instead of hash-hash bang-bangs.
First I have 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 gives 404 error, regardless if you clicked on the Navbar or typed the URL manually.
Am I doing something wrong? Thanks.
UPDATE: I added this code and it works fine now when I click on a link [stateful]. But if I refresh the page while I am in localhost:8000/contacts
I still get 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 have added the following route in my Express.js app. If you look closely you'll notice the URL bar changes from localhost:3000/#contact
to localhost:3000/contact
although it happens pretty fast. Perhaps there is a better way to do this thing, but I am satisfied with this approach for time being.
app.get('/contact', function(req, res) {
res.redirect('/#contact');
});
/contact
, etc, to the root page. – McGarnagle/contact
, the server returns the content for the root. I'm not familiar with Express/Node, so I don't know what the syntax would be ... – McGarnagle