Anna
Anna

Reputation: 45

How can I prevent 404 not found error in Angular when I refresh page?

I have an Angular project and when I upload it on a global server it returns me a 404 not found error when I refresh the page. How can I prevent this?

That's my routing.component.ts

import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';

import { PagesComponent } from './pages.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ECommerceComponent } from './e-commerce/e-commerce.component';
import { NotFoundComponent } from './miscellaneous/not-found/not-found.component';
import { createFalse } from 'typescript';

const routes: Routes = [
  
  
  {

  path: '',
  component: PagesComponent,
  children: [
    {
      path: 'dashboard',
      component: ECommerceComponent,
      
    },
    {
      path: 'iot-dashboard',
      component: DashboardComponent,
      
    },
    
    
    {
      path: '',
      redirectTo: 'iot-dashboard',
      pathMatch: 'full',
    },
    
    {
      path: '**',
      component: NotFoundComponent,
    },
  ],

}];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class PagesRoutingModule {
}

Upvotes: 1

Views: 5582

Answers (3)

If using Apache Server, add the following in a new .htaccess file next to index.html.

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

Last tested 2024.

Reason: SPAs load a single HTML file and dynamically update the content as the user interacts with the application, without reloading the entire page. Frameworks like React, Angular, and Vue.js are commonly used to build SPAs. The URL is interpreted by the browser to load example.org, and then the SPA's JavaScript code handles the path/component part to show the appropriate content. The server only needs to serve the initial HTML file, and the SPA handles the routing on the client side.

.htaccess helps in fallback to index.html if the given path is not a filename or directory.

Upvotes: 0

Kshitij
Kshitij

Reputation: 657

Just use angular's HashLocationStrategy.

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

Upvotes: 3

Sandman
Sandman

Reputation: 1569

You have to set up a fallback to index.html on the server (you didn't say which one is: Apache HTTPD? Nginx?): https://angular.io/guide/deployment#routed-apps-must-fallback-to-indexhtml

Upvotes: 2

Related Questions