允许Angular忽略某些URL

时间:2020-02-04 20:45:08

标签: angular typescript .htaccess search-guard

我的Angular应用程序在example.com上,我的后端在example.com/api上。我的问题是,当我想使用URL https://example.com/api/login/get-cookie向服务器发送请求时,出现HttpErrorResponse错误。我刚刚在浏览器中输入了相同的URL,但是我将被重定向到主页。所以我可能会收到此错误,因为永远无法访问我的服务器。

如何允许Angular忽略所有带有example.com/api/*的URL?

我的文件 app-routing.modules.ts 看起来像这样:

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

1 个答案:

答案 0 :(得分:2)

添加此重定向将采用与上面的路径不匹配的所有URL,并将其重定向到主页。或者,根据您的喜好,您可以创建404或错误组件,以显示{ 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' }
];