user677526
user677526

Reputation:

AngularJS routing with Mongoose webserver

I'm testing a website locally on my machine. It uses AngularJS for routing and page changes, and I'm attempting to test the routes using the Mongoose webserver (extremely light).

My code is as follows:

app.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
    $locationProvider.html5Mode(true);
    $routeProvider.when('/who', {templateUrl: '/js/partials/who', controller: 'whoPage'});
    $routeProvider.when('/what', {templateUrl: 'partials/what'});
    $routeProvider.when('/want', {templateUrl: 'partials/want'});
    $routeProvider.otherwise({ redirectTo: '/' });
}]);

(I haven't set up controllers for some of the other pages yet. I've been testing the "who" page.)

I'm running the page from localhost:8080. In my application, when I click a link to change the location, nothing happens. The URL changes to "localhost:8080/who", but I get no messages from console, and I get no changes on my page. However, if I then refresh that URL, I get a 404 error.

I don't have any server-side routing set up. Is this a necessity for Angular apps? Is there something wrong with the code I've written, or should I try a different test webserver?

Upvotes: 1

Views: 694

Answers (1)

mkm
mkm

Reputation: 1575

$locationProvider.html5Mode(true);

will make angular use "push state" from the HTML5 History API.

This means that you'll see the url change in the location bar, but that won't cause the browser to actually reload your page. When you reload the page, the browser will now fetch that url from the webserver, which doesn't have it.

A common trick is to use URL rewrites to map any url back to index.html. You should take care of not remapping the urls that point to static files such as your javascript and css resources. That's usually easy because it's a good practice to group all your css and js files in some directory instead of scattering them in the top level dir.

You can read about how to configure mongoose URL rewrites at https://www.cesanta.com/developer/binary#_url_rewrites

Upvotes: 0

Related Questions