Angular iis returns 上的 2 个应用程序 运行 重新加载时未找到

Angular 2 application running on iis returns not found when reload

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

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

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

IIS 也给出了这个响应:

Most probable causes: The directory or file specified does not exist on the Web server.

尝试在index.html中设置:

<head></head> 标签中:

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

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

希望对你有帮助!!

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

By default Angular 2 applications don't use a hash (#) prefix on urls, the effect of this is that if you try to navigate directly to a deep link in your angular app or refresh an internal page you may get a 404 page not found error. This is because the web server receiving the request looks for a resource matching the full url on the server, which doesn't exist because the angular portion of the url refers to a route in your angular application and needs to be handled in the client browser.

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

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

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

The way to fix this is by rewriting all virtual urls to the main Angular 2 index.html file.

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

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

<base href="/"/>