“Cannot get /routeName” (grunt-contrib-connect + Angular 2 Router)

I ran into this error when using Angular 2 Router with grunt-contrib-connect. After a bit of digging around, this is a super simple fix if you don’t require any advanced stuff.

It uses the middleware property.

It simply redirects all non file-type URLs to index.html which is the desired behaviour when using Angular 2 Router.

Credit to: DominikDitoIvosevic

Gruntfile.js (excerpt)

var rewrite = require('connect-modrewrite'); grunt.initConfig({ connect: { server: { options: { port: 9001, livereload: true, middleware: function(connect, options, middlewares) { var rules = [ '!\\.html|\\.js|\\.css|\\.svg|\\.jp(e?)g|\\.png|\\.gif$ /index.html' ]; middlewares.unshift(rewrite(rules)); return middlewares; } } } } });

It is pretty easy to add more exceptions if you need to, too:

var rules = [ '!\\.html|\\.js|\\.css|\\.svg|\\.jp(e?)g|\\.png|\\.gif|\\.pal$ /index.html' ];

Yes that was a Designated Survivor reference…

You could even write something to build this string if you wanted to be clever, so you could just list the exceptions like this:

var exceptions = [ '.html', '.js', '.css', // etc.... ];