【问题标题】:Why my angular app sometime show 404 error?为什么我的 Angular 应用程序有时会显示 404 错误?
【发布时间】:2021-06-28 23:30:43
【问题描述】:

我有一个使用 github 页面部署的站点,有时我收到 404 错误,这也发生在使用 ng serve --open 的 localhost 中

如果您是第一次尝试进入此页面,可能会遇到 404 错误:https://maximegillot.github.io/formation/kafka

但是如果你去主页:https://maximegillot.github.io/ 并手动导航到 /formation/kafka 你可能不会有任何问题......

当我使用ng serve --open部署我的站点时,我也遇到了这个问题

我觉得这个问题是随机的,我不知道从哪里开始调查。

要部署我只需使用 ng build --aot --vendor-chunk --common-chunk --delete-output-path --build-optimizer 并在 github 上发布 /dist/mgi-site/*https://github.com/MaximeGillot/MaximeGillot.github.io

我的index.html

<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Gillot Maxime</title>
  <base href="/">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"/>
  <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet"
        type="text/css"/>
  <link rel="icon" type="image/x-icon" href="assets/favicon.ico"/>
  <script src="https://use.fontawesome.com/releases/v5.15.3/js/all.js" crossorigin="anonymous">
...
</head>
<body>
<app-root></app-root>
</body>
</html>

文件app-routing.module.ts

const routes: Routes = [

  {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: 'formation/nifi', component: FormationNifiComponent},
  {path: 'formation/kafka', component: FormationKafkaComponent},
  {path: 'home', component: MainComponent},
  {path: 'cv', component: CvComponent},
  {path: 'projets', component: ProjetComponent}

];

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

【问题讨论】:

标签: html angular routes github-pages


【解决方案1】:

Angular 是一个单页应用程序,在不使用 # 的情况下部署时,托管站点会尝试在本地查找路径作为不存在的文件夹路径以及您收到 404 错误的原因。

如果您还没有,则需要设置一个 web.config 文件来处理重定向。

<?xml version="1.0" encoding="utf-8"?>
<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>

来源:

https://angular.io/guide/deployment#server-configuration https://indepth.dev/posts/1239/deploy-an-angular-application-to-iis

【讨论】:

  • githubPages没有使用IIS,而web.config是一个IIS文件...
猜你喜欢
  • 2014-06-25
  • 2010-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-28
  • 1970-01-01
相关资源
最近更新 更多