在 IIS 直接 url 上托管 Angular2 应用程序后无法正常工作

After hosting Angular2 app on IIS direct url is not working

我们开发了Angular2 App。

当我们在 angular-cli 和 'ng serve' 下 运行 时,它工作正常。

一旦我们将应用程序托管到 IIS 7.5,我们就可以毫无问题地浏览到应用程序的根目录,并且可以从创建的应用程序导航导航到任何其他视图。

但是,当用户尝试加载针对特定路由或组件的 url 时,问题就出现了。

所以如果我们去 http://serverurl ... it loads index.html and then clicking on navigation link on index.html it takes user to http://serverurl/route1/component1

但是当用户尝试在浏览器地址栏中转到 url http://serverurl/route1/component1 directly by typing http://serverurl/route1/component1 时,它会将该请求发送到 IIS,并且 returns 和找不到资源的错误。

而且很容易理解,服务器上不存在url。即angularurl。理想情况下,它应该加载 index.html 并将 url 的其余部分传递给 angular 路由器并加载 /route1/component1 。这适用于 'ng serve' 但不适用于 IIS 7.5。是否需要在 IIS 中进行任何设置才能使其正常工作?或者我必须在 Anuglar2 应用程序中做什么?

谁能告诉我如何解决这个问题?

我通过执行以下步骤解决了这个问题..

  1. 已从 https://www.microsoft.com/en-au/download/details.aspx?id=7435

  2. 下载 URL 重写器 模块
  3. 在我的web.config

  4. 中添加了以下内容

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

  1. 正在 index.html 中设置基本标签。它应该紧跟在 标签
  2. 之后

<base href="/"/>

这三个步骤将使您能够使用 html5mode 部署 Angular2 / Angular App url IIS 7.5 或 IIS 8.0

希望这会有所帮助。我必须回答几个问题才能解决这个问题。

我使用 Angular 4.0 和 IIS 6.1 进行了更简单的更改。这允许我使用命名站点而不是默认文件夹或上面的重写。我刚刚将基本 href 从“/”更改为我的应用程序文件夹的名称:

<head>
    <base href="MyApp">
...

希望这对其他人有用!

[windows 托管] 创建文本文件并将其命名为“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>

祝你好运 :) 当我为别人节省时间时,这是值得的!