在本地工作的远程服务器上,角度路由失败

时间:2020-08-03 11:25:56

标签: angular iis routes angular-routing angular9

我有一个非常简单的项目,该项目具有以下路由。

const routes: Routes = [
  { path: "start", component: StartComponent },
  { path: "sub01", component: Sub01Component },
  { path: "", redirectTo: "/start", pathMatch: "full" },
  { path: "**", component: StartComponent }
];

当我使用ng serve在本地运行并浏览到 localhost:4200 时,我看到了起始页的内容,并且URL被重写为 localhost:4200 / start ,正如预期的那样。然后,我通过 ng build 制作了一个半最终版本,并将其放在IIS上的 dist 目录中。浏览到应用程序的地址会产生与上述相同的结果。我还可以确认浏览到图片的网址也会产生预期的结果。

我注意到的区别是,在本地,它可以重新加载页面(即,浏览到 localhost:4200 / start ),而远程计算机上的相同操作失败,给我404(因此浏览 http://address.that-worked-just.now/start 无效)。由于我可以访问除根目录以外的其他URL,所以在我看来,这只是路由无效。

这种行为让我有些惊讶,并且不确定如何进一步诊断它。我所能了解的唯一区别是,在本地使用默认的Angular CLI为应用程序提供服务,而在远程使用包含 index.html 包含脚本的IIS。因此,我认为一旦将文档提供给客户,其他所有事情都会在客户身上发生。 (该应用程序确实很有限,并且与服务器,服务等都没有交互,因为它基本上是一个登陆页面,至少目前是这样。)

我是否缺少应在任何配置文件中声明的内容?还是由于某些防火墙策略或类似原因而可能发生怪异的错误行为?我不确定如何确定,我宁愿认为自己做了一些愚蠢的事情,而不是怪服务器团队。根据上面的描述,还有什么可以推断的?

1 个答案:

答案 0 :(得分:2)

IIS具有其自己的路由系统。因此,当我们在IIS中托管Angular时,Angular路由将会失败,因为IIS无法理解Angular路由,并且会寻找与该路由匹配的资源,并且会出现404错误。

要解决此问题,您可以尝试以下解决方案之一:

使用IIS URL重写规则来设置路由:

<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>

来源:https://angular.io/guide/deployment#fallback-configuration-examples

另一种方法是为404添加错误页面以重定向到/index.html。

enter image description here