【问题标题】:Angular 2 routing issue - 404 error on refresh or reloadAngular 2 路由问题 - 刷新或重新加载时出现 404 错误
【发布时间】:2017-09-09 14:15:51
【问题描述】:

我遇到了与角度路由相关的问题。所有页面都可以正常工作,但如果页面重新加载或刷新,则会出现 404 错误。我正在使用路径定位策略。我搜索了很多,但发现除了哈希位置策略之外的东西。我尝试过哈希位置策略,但在 url 中添加了 #(如 webiste.com/home#contact),但我想要不带 # 的 url。

我需要专家指导,因为我在搜索 3 4 天后被卡住了

提前致谢

【问题讨论】:

  • 您正在尝试使用本地主机或某些服务器?如果在服务器上,则必须将页面重定向到请求的页面,否则您知道哈希位置存在
  • 检查此链接可能会有所帮助。 Angular2 without hash in URL

标签: asp.net-mvc angular


【解决方案1】:

根据您使用的服务器,您需要将路由配置为始终指向 index.html。

当然你需要在index.html<head>中设置<base href="/">

如果您刷新 url site.com/myPage,服务器将尝试获取名称为 myPage 的资源,在您的情况下将返回 404。

WAMP 设置

Options -Indexes

RewriteEngine on

    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]
    RewriteRule ^(.*) index.html [NC,L]

IIS 设置

  <system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularJS Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

【讨论】:

  • 我正在使用窗口服务器,因为我的应用程序在 asp.net mvc 中
  • @JánHalaša 举了一个很好的例子。我将编辑我的 IIS 配置答案。
  • 谢谢@JánHalaša :-)
  • 干杯。很高兴它有帮助。
猜你喜欢
  • 2019-01-29
  • 2020-09-24
  • 2021-10-12
  • 1970-01-01
  • 2021-06-05
  • 2019-07-02
  • 2017-07-20
  • 2016-12-22
  • 2022-12-09
相关资源
最近更新 更多