Search code examples
angulartypescript.htaccesssearch-guard

Allow Angular to ignore some URLs


My application with Angular is on example.com and my backend is on example.com/api. My problem is when I want to send a request to the server with the URL https://example.com/api/login/get-cookie, I get an error of HttpErrorResponse. I have just typed the same URL in my browser but I will get redirected to the homepage. So I probably get this error, because my server can never be reached.

How can I allow Angular to ignore all URLs with example.com/api/*?

My file app-routing.modules.ts looks like this:

const routes: Routes = [
  { path: '', component: HomeComponent, canActivate: [HomeGuard] },
  { path: 'login', component: LoginComponent, canActivate: [LoginGuard] },
  { path: 'register', component: RegisterComponent, canActivate: [LoginGuard] },
  { path: 'search', component: SearchComponent, canActivate: [SearchGuard] },
  { path: 'edit-profile', component: ProfileComponent, canActivate: [SearchGuard] }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

.htaccess:

RewriteEngine On
    # If an existing asset or directory is requested go to it as it is
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
    RewriteRule ^ - [L]
    # If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

Solution

  • Adding this redirect will take any url that does not match the paths above and redirect them to the home page. Or depending on your preference you could create a 404 or Error component to show instead with { path: '**', component: ErrorComponent }

    const routes: Routes = [
      { path: '', component: HomeComponent, canActivate: [HomeGuard] },
      { path: 'login', component: LoginComponent, canActivate: [LoginGuard] },
      { path: 'register', component: RegisterComponent, canActivate: [LoginGuard] },
      { path: 'search', component: SearchComponent, canActivate: [SearchGuard] },
      { path: 'edit-profile', component: ProfileComponent, canActivate: [SearchGuard] },
      { path: '**', redirectTo: '/', pathMatch: 'full' }
    ];