在AngularJs SPA中,如何从URL中删除“.html”

时间:2013-12-13 12:33:57

标签: javascript angularjs url location single-page-application

我一直在研究这个问题已经有一段时间了,我已经遇到了一些相似但没有回答这个问题的Stackoverflow讨论让我满意。我不确定angularjs是否有办法做到这一点,但我确信在编写angularjs SPA应用程序时有一种方法可以做到这一点。这就是我的情况,

我正在为现有的基于ASP.NET MVC的应用程序编写AngularJs前端。 当前应用程序中的URL类似于

https://domain.com/login
https://domain.com/profile
https://domain.com/settings

我的新前端版本为

https://domain.com/index.html/login
https://domain.com/index.html/profile
https://domain.com/index.html/settings

我需要的问题是,

我需要从新网址中删除.html。这是我的第一个障碍。我稍后需要做的一切取决于我的URL读取方式。它需要以ASP.NET MVC提供的格式读取。 URL中没有.html文件扩展名的网址。

当我搜索关键字“angularjs url remove html and#!”

的建议时

我得到的前两个结果是

How to remove index.html from url on website based on angularjs

Removing the fragment identifier from AngularJS urls (# symbol)

在解决我的情况时,没有一个安静有帮助。

我正在考虑一种解决方法,如果没有更好的方法可以做到这一点,那就是

“由于Index.html是我的ng-view所在的位置,本质上这个页面驱动我的SPA架构,所以我可以进入我的IIS并将Index.html设置为默认文档”这样做有助于我实现我的目标想要(在URL中不显示“.html”)到一定程度。例如(在本地工作时)如果我导航到http://localhost,它将打开index.html,而不会在URL中显示文件名,只要我不刷新或复制粘贴,angularJs路由仍然可以正常工作这些URL(其中没有index.html)在这种情况下我得到404错误(当我使用$ locationProvider.html5Mode(true)删除#s时)。

这肯定不是理想的解决方案,因为当系统通过电子邮件向用户发送需要用来访问应用程序某些部分的URL时,我们总是需要在其中包含index.html(我们不希望这样)< / p>

任何帮助,非常感谢。感谢。

2 个答案:

答案 0 :(得分:0)

这是服务器方面的问题,而不是内容方面。您必须处理来自服务器端的请求,如下所示:

handle '/'
    return view 'index.html'

然后当您访问https://domain.com/时,您会看到index.html文件,但在网址中不会显示。

编辑

如果您正在使用angular的html5模式,那么您应该执行更复杂的路由,如下所示:

handle '/'
handle '/login'
handle '/profile'
handle '/settings'
    return view 'index.html'

因为例如您在网址:https://domain.com/profile并且您刷新了网页,请求将被发送到此网址,因此您还应处理'/profile'路由并返回相同的index.html页面(然后angularjs会关注路由)

如果您正在使用哈希(#),那么当您刷新https://domain.com/#/profile页面时,请求将被发送到https://domain.com/并且'/'路由处理程序就足够了

答案 1 :(得分:0)

您可以在web.config中编写URL重写规则:

    <rewrite>
      <rules>
        <rule name="Registration" stopProcessing="true">
          <match url="^Registration"/>
          <action type="Rewrite" url="/registration.html"/>
        </rule>
      </rules>
    </rewrite>
相关问题