Reloading the page gives wrong GET request with AngularJS HTML5 mode

Dieter De Mesmaeker picture Dieter De Mesmaeker · May 15, 2013 · Viewed 148.3k times · Source

I want to enable HTML5 mode for my app. I have put the following code for the configuration, as shown here:

return app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {

    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix = '!';

    $routeProvider.when('/', {
        templateUrl: '/views/index.html',
        controller: 'indexCtrl'
    });
    $routeProvider.when('/about',{
        templateUrl: '/views/about.html',
        controller: 'AboutCtrl'
    });

As you can see, I used the $locationProvider.html5mode and I changed all my links at the ng-href to exclude the /#/.

The Problem

At the moment, I can go to localhost:9000/ and see the index page and navigate to the other pages like localhost:9000/about.

However, the problem occurs when I refresh the localhost:9000/about page. I get the following output: Cannot GET /about

If I look at the network calls:

Request URL:localhost:9000/about
Request Method:GET

While if I first go to localhost:9000/ and then click on a button that navigates to /about I get:

Request URL:http://localhost:9000/views/about.html

Which renders the page perfectly.

How can I enable angular to get the correct page when I refresh?

Answer

James Sharp picture James Sharp · May 15, 2013

From the angular docs

Server side
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)

The reason for this is that when you first visit the page (/about), e.g. after a refresh, the browser has no way of knowing that this isn't a real URL, so it goes ahead and loads it. However if you have loaded up the root page first, and all the javascript code, then when you navigate to /about Angular can get in there before the browser tries to hit the server and handle it accordingly