AngularJS – Why when changing url address $routeProvider doesn't seem to work and I get a 404 error

All we need is an easy explanation of the problem, so here it is.

My $routeProvider is configured like this:

teachApp.config(['$routeProvider', '$locationProvider', function($routeProvider,       $locationProvider) {
    $routeProvider.
        when('/teach/', {templateUrl: 'views/login_view.html'}).
        when('/teach/overview', {templateUrl: 'views/overview_view.html'}).
        when('/teach/users', {templateUrl: 'views/users_view.html'}).
        otherwise({redirectTo: '/teach/'});
    $locationProvider.html5Mode(true);
}]);

Within the app, if I click on a link such as <a href="/teach/overview" rel="nofollow noreferrer noopener">Overview</a>, the overview partial shows as expected. However, when I manually change the URL in the address bar to exactly the same URL, I get a 404 error. Is $routeProvider incorrectly configured?

I’m using MAMP localhost with the root url of the app being http://localhost/teach/

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can also use # in your URLs.

http://localhost/teach/#/overview

This will not send a request to the server and will instead be intercepted by the Angular $routeProvider.

Method 2

You need to setup your apache to redirect all paths to root.

When you directly open http://localhost/teach/overview your web server is trying to serve a page from a route that is not defined.

When, within an angular app, you click on a link with href path of http://localhost/teach/overview, Angular steps in, and instead of letting your browser request a page from the server it intercepts your click event and goes to your routeProvider to see which client-side view to display (this is why they call it “single-page apps”). That’s why your links work as long as you try not to open them directly.

Beside the apache config you might also want to use base tag with href value of /teach/:

<base href="/teach/" rel="nofollow noreferrer noopener" />

so that you can have your routeProvider not constrained by fixed prefix:

teachApp.config(['$routeProvider', '$locationProvider', function($routeProvider,       $locationProvider) {
    $routeProvider.
        when('/', {templateUrl: 'views/login_view.html'}).
        when('/overview', {templateUrl: 'views/overview_view.html'}).
        when('/users', {templateUrl: 'views/users_view.html'}).
        otherwise({redirectTo: '/'});
    $locationProvider.html5Mode(true);
}]);

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply