Question

I have a connect server running on localhost, and in my backbone app, if I reload a route, say localhost:8000/fun the server returns Cannot GET /fun obviously because /fun doesn't exist.

Somehow the server needs to know to serve index.html/fun or something. I actually tried that, but I get some other error. Has anyone dealt with this before?

TL;DR Cannot GET /fun

Was it helpful?

Solution

So the basic solution was found here.

You want modRewrite:

npm install connect-modrewrite --save-dev

And in your Gruntfile:

modRewrite = require('connect-modrewrite')

Coffee:

connect:
  server:
    options:
      port: 8765
      open: true
      base: ['./']
      middleware: (connect, options) ->
        middlewares = []

        middlewares.push(modRewrite(['^[^\\.]*$ /index.html [L]']))
        options.base.forEach( (base) ->
          middlewares.push(connect.static(base))
        )
        middlewares

Vanilla JS:

connect: {
  server: {
    options: {
      port: 8765,
      open: true,
      base: ['./'],
      middleware: function(connect, options) {
        var middlewares;
        middlewares = [];
        middlewares.push(modRewrite(['^[^\\.]*$ /index.html [L]']));
        options.base.forEach(function(base) {
          return middlewares.push(connect["static"](base));
        });
        return middlewares;
      }
    }
  }
}

OTHER TIPS

Accepted answer didn't work anymore (2015-10-20), because there were changes to connect project-structure and connect.static was moved to its own package 'serve-static'. So you have to adapt this answer by the following:

npm install serve-static --save-dev

require it in your Gruntfile.js

var serveStatic = require('serve-static');

and then change the middleware code to following:

middleware: function(connect, options) {
      var middlewares;
      middlewares = [];
      middlewares.push( modRewrite( ['^[^\\.]*$ /index.html [L]'] ) );
      options.base.forEach( function( base ) {
        return middlewares.push( serveStatic( base ) );
      });
      return middlewares;
    }

Otherwise it works great! Helped me a lot!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top