Angular17 部屬完成,在瀏覽器中使用 F5 重新整理跳轉 404 異常解決


Posted by monoserve174 on 2023-12-28

筆者近日在將有興趣的 bootstrapmade 中的所提供的 bootstrap 改由 Angular 呈現,希望藉著這過程熟悉 Angular 的特性與部分的網頁效果的複現。之後文章內容僅會著重於遇到的問題與解決方法,或者說明一些檢討事項。

  • 問題描述: Angular 使用 ng build 進行部屬後,並使用 http-server 測試時,在頁面中的 Navbar 進行頁面切換皆為正常,但只要使用瀏覽器的重新整理(含F5)或直接在網址列中輸入網址,將直接轉向404錯誤。

  • 系統環境:

    • OS: Windows 10 x64
    • nodejs: v20.9.0
    • npm: 10.1.0
    • angular cli: 17.0.8
    • http-server: 14.1.1
  • 問題複現:

    1. 建立複現專案
      --style 指定樣式文件格式
      --routing 啟用網址管理
      -S (--skip-tests) 關閉單元測試
      ng new ng17-play --style=css --routing -S
    2. 進入專案中建立必要元件
      navbar、home、about
      ng g c navbar ng g c home ng g about
    3. 在初始元件引入 navbar 元件: src/app/app.component.ts
    4. 調整預設 layout: src/app/app.component.html
    5. 設定網址路徑: src/app/app.routes.ts
    6. 在 navbar 元件中引入 RouterLink: src/app/navbar/navbar.component.ts
    7. 調整 navbar 渲染內容: src/app/navbar/navbar.component.html
    8. 打包專案
      ng build
    9. 使用 http-server 測試
      cd dist\ng17-play\browser http-server
  • 解決方式:

    1. 調整網址路徑生成方式引入 withHashLocation: src/app/app.config.ts
    2. 重新打包
      ng build
    3. 重新啟動 http-server
      cd dist\ng17-play\browser http-server
    4. 瀏覽器清除暫存後重新載入
  • 解決原因: Angular 為單頁應用程式(SPA),如果直接在瀏覽器中重新整理,瀏覽器則直接跳過 index.html 文件進行畫面渲染,因而導致,無法存取畫面。而 Angular 提供的解決方式為所有頁面都加個/#/,迫使瀏覽器每次都進 index.html 中再判斷該取得哪個元件資訊。

  • 參考資料


#angular build #web deploy #http-server #angular17







Related Posts

 Spread Operator

Spread Operator

第十一天:權息通服務網站【二】

第十一天:權息通服務網站【二】

SCSS - map vs list / @for vs @each

SCSS - map vs list / @for vs @each


Comments