Search code examples
angulartypescriptangular-routing

How to fix Cannot GET / in Angular when refreshing the page?


I'm new in the Angular world. I followed Angular.io guide for routing my application and its many pages. The issue I have is when I hit the refresh button in the browser. I a "Cannot GET /dashboard" I have been researching about this issue and I do have the href="/" in placed.

This is my routing file

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: '', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },

  { path: '**', redirectTo: '', pathMatch: 'full' }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      routes,
      {
        enableTracing: false
      }
    )],
  exports: [RouterModule]
})
export class AppRoutingModule { }

As mentioned before, I can get to the url but when I refresh the page I get the "Cannot GET /dashboard" Is there anything special I need to do to fix this issue? How to fix Cannot GET / in Angular when refreshing the page?


Solution

  • Your server needs to be set up to return the base HTML page no matter the URL, so the client side router can then see /dashboard and take it from there. Otherwise, when you go directly to /dashboard your server will think you're asking it for a dashboard page.

    You could accomplish this in IIS using URL rewrites. Here's an example from https://blog.angularindepth.com/deploy-an-angular-application-to-iis-60a0897742e7:

    <system.webServer>
      <rewrite>
        <rules>
          <rule name="Angular Routes" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAll">
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            </conditions>
            <action type="Rewrite" url="./index.html" />
          </rule>
        </rules>
      </rewrite>
    </system.webServer>
    

    Another option is hash-based URLs, which can be accomplished like this:

    RouterModule.forRoot(routes, { useHash: true })
    

    This works because the server doesn't see the hash portion of the URL. See https://angular.io/guide/router for details.