You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular开发Ionic PWA页面加载出404错误但可正常显示

问题描述

使用Angular开发Ionic PWA时,应用加载及切换页面时控制台频繁出现Failed to load resource: the server responded with a status of 404 (Not Found)错误,页面虽能加载但耗时较长。构建后用http-server www/运行时,终端也会输出404日志:

[2022-11-02T14:10:30.741Z]  "GET /admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36"
[2022-11-02T14:10:30.744Z]  "GET /admin" Error (404): "Not found"

本地开发环境无此错误,但浏览器无法找到service worker,无法使用PWA功能。已检查路由守卫AuthGuard正常跳转,在app.module.ts中配置了PathLocationStrategy,使用ionic build --prod && http-server www/构建运行。


相关代码配置

app-routing.module.ts

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './guard/auth.guard';

const routes: Routes = [
  {
    path: '',
    redirectTo: 'tabs',
    pathMatch: 'full'
  },
  {
    path: 'tabs',
    loadChildren: () => import('./pages/tabs/tabs.module').then( m => m.TabsPageModule),
    canLoad: [AuthGuard],
    data: {
      type: 'user',
    }
  },
  {
    path: 'login',
    loadChildren: () => import('./pages/login/login.module').then( m => m.LoginPageModule)
  },
  {
    path: 'admin',
    loadChildren: () => import('./pages/admin/admin.module').then( m => m.AdminPageModule),
    canLoad: [AuthGuard],
    data: {
      type: 'admin'
    }
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts相关配置

import { PathLocationStrategy, LocationStrategy } from '@angular/common';

...

  providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy},
    {provide: LocationStrategy, useClass: PathLocationStrategy} 
  ],

admin-routing.module.ts

import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';
import { DayPilotModule } from '@daypilot/daypilot-lite-angular';

import { AdminPage } from './admin.page';

const routes: Routes = [
  {
    path: '',
    component: AdminPage
  },
  {
    path: 'add-photo',
    loadChildren: () => import('./add-photo/add-photo.module').then( m => m.AddPhotoPageModule)
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(routes),
    FormsModule,
    DayPilotModule,
    HttpClientModule
  ],
  exports: [RouterModule],
})
export class AdminPageRoutingModule {}

版本信息

Versions:

Angular CLI: 13.3.3
Node: 17.8.0 (Unsupported)
Package Manager: npm 8.19.2
OS: darwin arm64

Angular: 13.3.4
... core

Package                             Version
-------------------------------------------------------------
@angular-devkit/architect           0.1303.3
@angular-devkit/build-angular       13.3.9
@angular-devkit/core                13.3.3
@angular-devkit/schematics          13.3.3
@angular/animations                 7.2.16
@angular/cdk                        14.2.4
@angular/cli                        13.3.3
@angular/common                     13.3.3
@angular/compiler                   13.3.3
@angular/compiler-cli               13.3.3
@angular/fire                       7.3.0
@angular/forms                      13.3.3
@angular/language-service           13.3.3
@angular/material                   14.2.4
@angular/platform-browser           13.3.3
@angular/platform-browser-dynamic   13.3.3
@angular/router                     13.3.3
@angular/service-worker             13.3.3
@schematics/angular                 13.3.3
rxjs                                6.6.7
typescript                          4.4.4


Ionic:

   Ionic CLI                     : 6.20.3 
   Ionic Framework               : @ionic/angular 6.3.3
   @angular-devkit/build-angular : 13.3.9
   @angular-devkit/schematics    : 13.3.3
   @angular/cli                  : 13.3.3
   @ionic/angular-toolkit        : 6.1.0

排查建议

1. 解决PathLocationStrategy导致的404问题

使用PathLocationStrategy时,http-server默认不会将路由请求重定向到index.html,导致刷新或直接访问子路由(如/admin)时出现404。

  • 启动http-server时添加-P参数配置重定向规则:
    ionic build --prod && http-server www/ -P http://localhost:8080?
    
    该参数会将所有404请求重定向到index.html,由Angular路由处理。

2. 修复Service Worker无法加载的问题

  • 检查ngsw-config.json是否存在且配置正确,确保所有静态资源和路由都被正确纳入缓存范围。
  • 构建时确认Service Worker已生成:查看www/ngsw-worker.js和www/ngsw.json文件是否存在,若缺失,重新执行ionic build --prod,或检查app.module.ts中是否导入了ServiceWorkerModule并正确配置:
    import { ServiceWorkerModule } from '@angular/service-worker';
    import { environment } from '../environments/environment';
    
    @NgModule({
      imports: [
        ...
        ServiceWorkerModule.register('ngsw-worker.js', {
          enabled: environment.production,
          registrationStrategy: 'registerWhenStable:30000'
        })
      ]
    })
    
  • 确保http-server以https协议运行(Service Worker要求HTTPS环境,localhost除外),若需测试HTTPS,可使用http-server -S -C cert.pem www/(需自行生成证书)。

3. 优化页面加载耗时

  • 调整路由预加载策略:当前使用PreloadAllModules会预加载所有懒加载模块,若模块较多会增加初始加载时间。可改为PreloadSelectedModules仅预加载常用模块,或改为按需加载。
  • 检查AuthGuard逻辑:若canLoad中存在异步请求(如用户权限验证),确保请求高效,避免阻塞路由加载。
  • 优化静态资源:启用Ionic资源压缩,移除未使用依赖(如@angular/animations版本7与Angular13不兼容,建议升级到同主版本)。

4. 版本兼容性检查

  • Node版本17.8.0为非支持版本,建议降级到LTS版本(如16.x),避免构建或运行时潜在问题。
  • @angular/animations版本7.2.16与Angular13存在版本差异,升级到13.x版本:
    npm install @angular/animations@13.3.4
    
  • @angular/cdk和@angular/material版本14.2.4与Angular13不兼容,建议降级到13.x版本,避免运行时错误。

内容的提问来源于stack exchange,提问作者Veronika Anna Kercsmár

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:45:52