【问题标题】:Allow Angular to ignore some URLs允许 Angular 忽略某些 URL
【发布时间】:2020-02-04 20:45:08
【问题描述】:

我的 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

【问题讨论】:

    标签: angular typescript .htaccess search-guard


    【解决方案1】:

    添加此重定向将采用与上述路径不匹配的任何 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' }
    ];

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      • 2019-05-30
      • 2014-07-09
      相关资源
      最近更新 更多