4

An Express / route serves my Backbone's app index.html.

I'm using pushstate in Backbone but the routes that Backbone should handled are being handled by express, giving 404 responses.

How can I setup Express to serve the index.html but to delegate other routes to Backbone?

4
  • 1
    Have you taken a look at the solution used by Backbone boilerplate? stackoverflow.com/questions/9328513/backbone-js-and-pushstate Feb 23, 2013 at 1:55
  • @WiredPrairie That only works when clicking anchors
    – jviotti
    Feb 23, 2013 at 2:11
  • You still need to do server side routes if a client is visiting that route directly. Even if it's just serving up index.html; the server has to know what to do with it. Feb 23, 2013 at 2:16
  • In a non-nodejs app, I just rewrote the URLs to include the #route in the other case. So, when it wasn't some special routes (like for REST API calls), a URL like /orders/123 became rootpage.html#orders/123 (Sorry, forgot to add that detail the 1st time). Feb 23, 2013 at 2:24

2 Answers 2

3

In this situation you have multiple options:

  1. You can have a server that handles the same routes as the client does and returns the same results. It is hard to implement but it gives a good url. Github did this.

  2. Always return index.html and handle the route client side. (That is somewhat ugly and hard to maintain)

  3. Don't use pushstate. Amen.

3
  • Using node/express, how can I accomplish the second option, routing all requests back to index.html? Jul 31, 2013 at 0:02
  • You can use regexp in your routes. So lets say that you want to send index.html for all get request you could use: app.get("/*", function(){...)}). I personnally don't like this method since you can't have any other get request, but you could have a better regexp and omit some routes. Jul 31, 2013 at 5:10
  • Or you could just use res.format - serve the json requests as you've been doing, but res.redirect the html requests back to the root stackoverflow.com/a/8928993/1094784
    – Petrov
    Aug 19, 2013 at 22:21
1

You can use /* approach. Just have it as the last route. That way the other routes such as any service API calls will be matched before the catch all route of /* is matched. This is also how Backbone handles its routes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.