0

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

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

我的文件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
4

1 回答 1

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' }
];

于 2020-02-04T20:52:00.300 回答