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?

jviotti
  • 17,881
  • 26
  • 89
  • 148
  • 1
    Have you taken a look at the solution used by Backbone boilerplate? http://stackoverflow.com/questions/9328513/backbone-js-and-pushstate – WiredPrairie Feb 23 '13 at 01:55
  • @WiredPrairie That only works when clicking anchors – jviotti Feb 23 '13 at 02: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. – Andrew Kirkegaard Feb 23 '13 at 02: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). – WiredPrairie Feb 23 '13 at 02:24

2 Answers2

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.

Community
  • 1
  • 1
Jean-Philippe Leclerc
  • 6,713
  • 5
  • 43
  • 66
  • Using node/express, how can I accomplish the second option, routing all requests back to index.html? – chandlervdw Jul 31 '13 at 00: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. – Jean-Philippe Leclerc Jul 31 '13 at 05: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 http://stackoverflow.com/a/8928993/1094784 – Petrov Aug 19 '13 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.

Saint48198
  • 121
  • 2