Angular 2& Google App Engine,设置基本href,重新加载子路由失败,服务器端路由

时间:2017-02-01 17:35:41

标签: google-app-engine angular angular2-routing

编辑:请参阅下面的答案。由于Google App Engine中的路由问题,这是服务器端问题,而非客户端相关问题。

我有一个Angular-CLI ng2应用,我设置了<base href="/admin/">

在路由时,一切都能正常运行。但是,当我在/admin/forms之类的子路由上并且我重新加载页面时,我收到404错误,该资源不可用。

来自app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {DashboardComponent} from "./main/dashboard/dashboard.component";
import {AdminComponent} from "./main/admin/admin.component";
import {FormsComponent} from "./main/components/forms/forms.component";

const routes: Routes = [
  {
    path: '',
    component: AdminComponent,
    children: [
      {
        path: '',
        component: DashboardComponent,
      },
      {
        path: 'forms',
        component: FormsComponent
      },
    ]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: []
})
export class RoutingModule { }

来自控制台错误日志:

Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:8080/admin/forms

使用app.yaml(Google App Engine)进行服务器端路由:

handlers:
- url: /admin/(.+)
  static_files: dist/\1
  upload: dist/(.*)
- url: .*
  static_files: dist/index.html
  upload: dist/index.html

错误仅发生在从子路由重新加载页面或尝试直接访问URL时。从sidenav服务访问路由时,页面正确加载。

1 个答案:

答案 0 :(得分:4)

我正在关联this SO post以及jay khimani's blog以了解我收到错误的原因。

错误与Angular 2无关,但是Google App Engine的app.yaml处理程序中的正则表达式排序不正确。

我最初使用Jay的博客来设置我的app.yaml处理程序:

handlers:
  - url: /admin/(.+)
    static_files: dist/\1
    upload: dist/(.*)
  - url: .*
    static_files: dist/index.html
    upload: dist/index.html

但是,我手动加载的任何路由都会被第一个正则表达式(/admin/(.+))捕获。因此,我更改了提供静态文件的路由更具体:

handlers:
  - url: /(.*\.(js|map|css|png))$
    static_files: dist/\1
    upload: dist/.*\.(js|map|css|png)$

  - url: .*
    static_files: dist/index.html
    upload: dist/index.html

这为我解决了路由页面重新加载问题。