Angular 項目打包之后,部署到服務器,刷新訪問404解決方法


將前端代碼打包部署到服務器中,當跳轉到相應路由界面,刷新地址,服務找不到地址頁面,所以會報   404 - Page Not Found。

解決方法:只需要將路由轉換成哈希值: userHash: true,將路由轉化成“#”號的形式

以下兩種方式修改路由,使用hash:

1、sys-routing.module.ts

imports: [
    RouterModule.forRoot(routers, {useHash: true})
]

2. app.module.ts文件添加兩行代碼:

import { LocationStrategy, HashLocationStrategy } from '@angular/common';
@NgModule({
 
    providers: [
 
    { provide: LocationStrategy, useClass: HashLocationStrategy },
 
    ]
 
})

3.因為后台是基於.net core,發布於iis,故添加web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  有關如何配置 ASP.NET 應用程序的詳細信息,請訪問
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>

  <system.webServer>
     <rewrite>
    <rules>
      <rule name="Angular Routes" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/index.html" />
      </rule>
    </rules>
  </rewrite>
  </system.webServer>

</configuration>

個人使用3完成

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularJS" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

非asp.net 個人推薦 2   原文Copy自:此位大佬


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM