首页 > 解决方案 > Firebase 上托管的 Ionic 4 应用程序仅在重新加载时返回 404

问题描述

我使用 @angular/pwa、firebase 托管和这个非常有用的教程创建了一个 Ionic 4 PWA。

在遵循教程中的所有说明(并将我的应用程序构建到“www”文件夹中)之后,我使用 CLI 中的“firebase deploy”将我的工作 Ionic 4 应用程序部署到这个工作链接。

问题是:在第一次访问页面时,一切都完美无缺。但是当我重新加载页面或使用搜索栏访问页面时(例如,输入“ https://..link../login ”),Firebase 会返回 404 错误。

该文件不存在,并且在当前目录中找不到 index.html 或根目录中的 404.html。

在控制台中:

加载资源失败:服务器响应状态为 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 {}

我能做些什么来解决这个错误?

标签: angularfirebaseionic-frameworkfirebase-hostingionic4

解决方案


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

您需要rewritefirebase.json.

像这样的东西应该工作

{
  "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"
          }
        ]
      }
    ]
  }
}

推荐阅读