Dieter De Mesmaeker Dieter De Mesmaeker - 1 year ago 286
AngularJS Question

Reloading the page gives wrong GET request with AngularJS HTML5 mode

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.hashPrefix = '!';

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

As you can see, I used the
and I changed all my links at the ng-ref to exclude the

The Problem

At the moment, I can go to
and see the index page and navigate to the other pages like

However, the problem occurs when I refresh the
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
and then click on a button that navigates to
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?

Thank you in advance.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download