【问题标题】:AngularJS pretty Urls routing on refreshAngularJS漂亮的Urls路由刷新
【发布时间】:2016-02-07 21:56:55
【问题描述】:

我在 AngularJS 中使用漂亮的 URL 路由,这是我的 angularJS 代码

var app = angular.module('app.home', ['ngRoute', 'ngAnimate']);

app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
    $routeProvider.
        when('/', {
            templateUrl: 'static/home.html',
            controller: 'AppController'
        }).
        when('/about', {
            templateUrl: 'static/about.html',
            controller: 'AppController'
        }).
        when('/contact', {
            templateUrl: 'static/contact.html',
            controller: 'AppController'
        }).
        when('/tutorial', {
            templateUrl: 'static/tutorial.html',
            controller: 'AppController'
        }).
        otherwise({
            redirectTo: '/'
        });

    $locationProvider.html5Mode(true);
}]);

app.controller('AppController', function ($scope) {

});

它工作正常,但是当我导航到 /about(或除“/”以外的任何 url)并点击刷新时,它显示服务器找不到资源错误。我正在使用 ASP.NET 5。有什么方法可以重定向到用户在刷新后点击刷新的那个页面?

【问题讨论】:

  • '/about' 没有模板网址,您可以通过多种方式修复它,如下面的答案所示。也许你会发现ui-router 很有用。

标签: javascript html asp.net angularjs iis


【解决方案1】:

您需要配置您的服务器以返回与您的 angularjs 路由匹配的任何路由的主 html 文件。所以你的服务器应该返回 /index.html 或任何你的文件,对于任何请求:/about、/tutorial、...等

【讨论】:

    【解决方案2】:

    确保在您的 web.config 中包含正确的重写

    <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" />
                <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
              </conditions>
              <action type="Rewrite" url="/" />
            </rule>
          </rules>
        </rewrite>
      </system.webServer>
    

    确保在您的&lt;head&gt; 中也包含&lt;base href="/"&gt;(或其他适用的,如果使用>1.2.x)。诶? Why would we need that?


    以下简短的博客文章是一篇不错的文章,它用简单的术语分解了我们为什么需要这样做...

    Deep Linking AngularJS on Windows Azure IIS


    关于 ASP.NET 5,web.config 仍然受支持,但它应该进入 wwwroot 文件夹。您可能缺少 IIS 的 Url Rewrite 模块。

    【讨论】:

    • 感谢您的回复。实际上我使用的是 ASP.NET 5。所以 web.config 被 config.json 替换。你能告诉我 web.config 的 JSON 代码吗?
    • 您应该只添加一个 web.config 文件。你能试着让我知道这是否有效吗?查看this similar question
    • 对不起,在 ASP.NET 5 中没有 web.config 文件的选项。它只支持 config.json。
    • 你试过了吗?你看我提供的问题链接了吗?如果您不打算尝试添加.config 文件,您就不能将 xml 转换为 json 并粘贴吗?
    • see this 如果这能解决您的问题,请告诉我
    猜你喜欢
    • 2016-01-30
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 2016-11-30
    • 1970-01-01
    • 2013-05-24
    相关资源
    最近更新 更多