user08
user08

Reputation: 735

Angular 2 routes not working after building the project

These are my routes:

import { Routes } from '@angular/router';
import {WelcomeComponent} from "./welcome/welcome.component";
import { LoginComponent } from './login/login.component';

export const routes: Routes = [
  {path: '', component: WelcomeComponent},
  {path: 'login', component: LoginComponent},
  {path: '**', component: WelcomeComponent}
];

I buid my project using ng buid.

When I enter a not defined path, I expect the application to redirect to '/' path as it happens during development, but I get an 404 Error.

I get the same error even when I manually enter /login URL.

What am I missing?

Upvotes: 5

Views: 7128

Answers (4)

Ruben Szekér
Ruben Szekér

Reputation: 1175

For me the problem was fixed when I changed the build command from ng build to ng build --prod. Ofcourse you cannot use this solution when you need the build to function outside of the production environment.

Upvotes: 0

user08
user08

Reputation: 735

As @Milad stated I had to redirect all get request to index.html. Adding .htacces file solved my issue:

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

Upvotes: 8

Milad
Milad

Reputation: 28592

You need to make sure if you're serving your app via a express server or any other web server , you should redirect all the get requests to index.html.

As long as your server is not redirecting all the requests to index.html, it doesn't matter what's happening inside your Angular app.

Upvotes: 7

not2savvy
not2savvy

Reputation: 4243

If you want to redirect, you should specify exactly that:

  { path: '**', redirectTo: '/'}

However, I recommend something like:

  {path: '/welcome', component: WelcomeComponent},
  {path: '/login', component: LoginComponent},
  {path: '**', redirectTo: '/welcome'}

Also note the leading slashes in the path.

Upvotes: 1

Related Questions