Reputation: 6499
I'm building a site using Express and Backbone.js. I'd like to handle as much as I can on the front-end.
One thing that I'm confused about, is how to defer routing requests to Backbone rather than Express. I understand that Backbone can now handle routes such as '/this/here', but of course Express interprets that first.
What's the best way to hand that off to Backbone? Should I create a global route in Express that handles everything I don't specifically define?
Upvotes: 3
Views: 3011
Reputation: 1959
Not sure why the first answer is accepted, but that is not correct. There are two ways to handle this.
user a catch all get in your node express routes
app.get "*", (req, res) ->
res.render "index"
use a catch all use in your node express routes
app.use (req, res) ->
res.render "index"
Either of these should be at the end of all your routes so that any other get's for either pages or API endpoints will still be called. Your client side MVC router will then go to the correct page.
Upvotes: 8
Reputation: 2925
The trick is that your application needs to know which routes to intercept on the client side (e.g. using Backbone) and the server-side (e.g. using node.js/Express.js). This is done by using a hash ('#') in the URL for links which should be caught by Backbone. URLs not containing the hash will be sent to the server.
The following is an example of how to add routes to the Backbone router object. I have also added a default route ('*path'), which allows Backbone to catch any other paths on the client-side. Note that this default setting only works for URLs containing a hash ('#'):
// Configure router.
var AppRouter = Backbone.Router.extend({
routes: {
'contact/add': 'addContact',
'*path': 'defaultPage'
},
addContact: function() {
$content.html('Add');
},
defaultPage: function(path) {
$content.html('Default');
},
});
// Initialize router.
var appRouter = new AppRouter();
Backbone.history.start();
The corresponding html link would be written as:
<a href='/#contact/add'>Add</a>
Upvotes: 0
Reputation: 2565
i may be completely mistaken but express is a server-side framework while backbone is a client-side framework.
only server-side frameworks are responsible for routing in the sense of analyzing incoming requests and delivering resources.
i think, what you are refering to is resource routing (coming out of the ruby on rails world) support inside express, that is, every resource in your application is available at a restful url like /posts
.
you can than GET, POST, PUT, DELETE this resource and the framework dispatches those types right to the correct business logic.
routes in backbone.js are (as of my understanding) pure client-side routes which enable you to have a working browser history while building a full-fledged ajax application.
i hope it got clear that both things, although named the same, are not exactly the same.
Upvotes: -1