【问题标题】:Angular 2 application running on iis returns not found when reload重新加载时在 iis 上运行的 Angular 2 应用程序返回未找到
【发布时间】:2017-08-21 11:25:39
【问题描述】:

我在 IIS 中创建了一个新页面。我将物理路径连接到我的 angular 2 应用程序源。

当我使用localhost:port 访问该页面时,我可以正常访问该页面。

当我切换到其他视图时,例如localhost:port/Employees,起初它可以正常工作,但是当我重新加载页面时,它返回相同 URL 的 HTTP-404 错误。有人遇到过这个问题吗?我认为这与 Angular 2 路由有关。

IIS 也给出了这样的响应:

最可能的原因:指定的目录或文件在 Web 服务器上不存在。

【问题讨论】:

  • 如果您想要有用的答案,您可能需要发布一些代码。我建议阅读How do I ask a good question?,然后编辑您的问题以在其中包含建议。

标签: angular typescript iis routing iis-express


【解决方案1】:

这不是 Angular Routing 的问题。这是必须在服务器端处理的事情。进行刷新时,服务器应重定向到基本路径。

默认情况下,Angular 2 应用程序不会在 url 上使用哈希 (#) 前缀, 这样做的效果是,如果您尝试直接导航到深处 在您的 Angular 应用程序中链接或刷新内部页面,您可能会收到 404 页面未找到错误。这是因为 Web 服务器接收到 请求在服务器上查找与完整 url 匹配的资源, 不存在,因为 url 的角度部分指的是 在您的角度应用程序中路由,需要在 客户端浏览器。

在 Angular 中可以使用 HashLocationStrategy 解决此问题。

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
    bootstrap: [AppComponent],
})

Angular 2 + IIS - URL 重写规则以防止页面刷新后出现 404 错误

解决这个问题的方法是将所有虚拟 url 重写到主 Angular 2 index.html 文件。

<rewrite>
  <rules>
    <rule name="Angular" 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>

【讨论】:

  • 但是这种配置总是会将页面重定向到主视图还是我刷新/重新加载的那个?
  • @OjamaYellow 这是一个变通方法而不是解决方案,因为这是必须由服务器配置处理的事情。或者更好地使用HashLocationStrategy
【解决方案2】:

尝试在index.html中设置:

&lt;head&gt;&lt;/head&gt;标签中:

<base href="./" /> or  <base href="/" />

webconfig 文件中设置你的index.html 为default page

希望对你有帮助!!

【讨论】:

    【解决方案3】:

    如果您不在 url 中使用哈希,则需要您的服务器来处理它。如果未找到请求的页面,您的服务器需要回退到 index.html。你也需要

    <base href="/"/>
    

    【讨论】:

      猜你喜欢
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      • 2018-08-02
      • 1970-01-01
      • 2018-04-11
      • 2016-10-25
      • 1970-01-01
      相关资源
      最近更新 更多