Ionic 4 应用托管在 Firebase returns 404 仅在重新加载时

Ionic 4 app hosted on Firebase returns 404 ONLY on reload

我使用@angular/pwa、firebase 托管创建了一个 Ionic 4 PWA,这非常 helpful tutorial.

按照教程中的所有说明进行操作(并将我的应用程序构建到 'www' 文件夹中)后,我使用 'firebase deploy' 将我的工作 Ionic 4 应用程序部署到 this working link命令行界面。

问题是:第一次访问该页面时,一切正常,没有任何缺陷。但是,当我重新加载页面或使用搜索栏访问页面时(例如,输入“https://..link../login”)Firebase returns 给我一个 404 错误。

This file does not exist and there was no index.html found in the current directory or 404.html in the root directory.

在控制台中:

Failed to load resource: the server responded with a status of 404 ()

我的firebase.json:

{
  "hosting": {
    "public": "www",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "headers": [
      {
        "source": "/build/app/**",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "public, max-age=31536000"
          }
        ]
      },
      {
        "source": "sw.js",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "no-cache"
          }
        ]
      }
    ]
  }
}

我的Angular路由模块:(app-routing-module.ts)

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  { path: '', loadChildren: './tabs/tabs.module#TabsPageModule' },
  { path: 'landing', loadChildren: './landing/landing.module#LandingPageModule' },
  { path: 'add-event', loadChildren: './add-event/add-event.module#AddEventPageModule' },
  { path: 'signup', loadChildren: './signup/signup.module#SignupPageModule' },
  { path: 'login', loadChildren: './login/login.module#LoginPageModule' },
  { path: 'add-profile', loadChildren: './add-profile/add-profile.module#AddProfilePageModule' }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

我该怎么做才能解决这个错误?

Angular/Ionic 应用程序将所有流量定向到 index.html 文件并将请求从那里路由到正确的 module/component。当您尝试访问 https://applifybyamplify.firebaseapp.com/login 时,firebase 正在寻找文件夹 ./login/index.html,因此您会收到 404.

您需要在 firebase.json 中使用 rewrite 规则。

像这样的东西应该可以工作

{
  "hosting": {
    "public": "www",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [   
      {
        "source": "**",
        "destination": "/index.html"
      }
    ],
    "headers": [
      {
        "source": "/build/app/**",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "public, max-age=31536000"
          }
        ]
      },
      {
        "source": "sw.js",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "no-cache"
          }
        ]
      }
    ]
  }
}