Search code examples
angularangular2-routing

Angular 2: 404 error occur when I refresh through the browser


I have stored my single-page application in my server within a folder named as "myapp". I have changed the URL in the base to http://example.com/myapp/`.

My project has two pages. So I implement Angular 2 routing. I set the default page as login. When I type http://example.com/myapp/ in my browser it will redirect automatically to http://example.com/myapp/login. But if refresh that page I get a 404 error, saying that http://example.com/myapp/login is not found.

But if I run my project using the lite server everything is working. In this case the base URL in index.html will be "/". How do fix it?


Solution

  • In fact, it's normal that you have a 404 error when refreshing your application since the actual address within the browser is updating (and without # / hashbang approach). By default, HTML5 history is used for reusing in Angular2.

    To fix the 404 error, you need to update your server to serve the index.html file for each route path you defined.

    If you want to switch to the HashBang approach, you need to use this configuration:

    import {bootstrap} from 'angular2/platform/browser';
    import {provide} from 'angular2/core';
    import {ROUTER_PROVIDERS} from 'angular2/router';
    import {LocationStrategy, HashLocationStrategy} from '@angular/common';
    
    import {MyApp} from './myapp';
    
    bootstrap(MyApp, [
      ROUTER_PROVIDERS,
      {provide: LocationStrategy, useClass: HashLocationStrategy}
    ]);
    

    In this case, when you refresh the page, it will be displayed again (but you will have a # in your address).

    This link could help you as well: When I refresh my website I get a 404. This is with Angular2 and firebase.

    Hope it helps you, Thierry