了解从角度路由中删除哈希#所需的内容

时间:2014-11-12 19:16:11

标签: angularjs angular-routing

在删除哈希标志之前,我有

mainApp.config(function ($locationProvider, $routeProvider) {
    $routeProvider
    .when('/page', {
        controller: 'Page',
        templateUrl: 'templates/page.html'
    })
    .when('/main', {
        controller: 'Main',
        templateUrl: 'templates/main.html'
    })
    .otherwise({ redirectTo: '/main'});

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

这些工作正常

http://localhost:8080/index.html#/main
http://localhost:8080/index.html#/page

删除井号后,我添加到index.html

<base href="/">
<script src="/vendor/bootstrap-dist/js/bootstrap.min.js"></script>
<script src="/vendor/javascript/angular/angular.js"></script>
<script src="/vendor/javascript/angular/angular-route.js"></script>
<script src="/vendor/javascript/angular/ui-bootstrap-tpls-0.11.2.min.js"></script>
<script src="/javascript/index.js"></script>
<script src="/javascript/controllers/main.js"></script>
<script src="/javascript/controllers/page.js"></script>

和index.js

$locationProvider.html5Mode(true);

现在点击http://localhost:8080重定向到http://localhost:8080/main

但直接在浏览器中转到http://localhost:8080/main会返回404,其他页面也会返回

我该怎么做才能解决问题?

我的后端是java

1 个答案:

答案 0 :(得分:5)

这是预期的。以下是未打开html5时发生的情况:

  • 您在地址栏中输入了网址http://localhost:8080/index.html#/main
  • 浏览器向localhost:8080 / index.html发出http请求并获取html页面作为回复
  • html页面包含一个已执行的角度应用程序。角度路由器在散列(/ main)之后解析路径,从而加载关联的视图和控制器

现在启用html5模式并加载index.hml会发生什么?

  • 您在地址栏中输入了网址http://localhost:8080/index.html
  • 浏览器向localhost:8080 / index.html发出http请求并获取html页面作为回复
  • html页面包含一个已执行的角度应用程序。角度路由器解析路径(/index.html),发现它与任何路由都不匹配,因此将地址栏中的位置更改为默认值:/ main,然后加载关联的视图和控制器。更改地址栏中的位置不会使浏览器执行除导航历史记录中添加新条目以外的任何操作。

现在,如果您点击刷新,或直接在地址栏中输入http://localhost:8080/main会怎样?那么在这种情况下,你说的是浏览器:“请在网址http://localhost:8080/main加载页面。这就是浏览器的作用:它向http://localhost:8080/main发送HTTP请求。由于服务器没有'在这个地址有任何东西,它会发回404。

现在如何让它发挥作用?它实际上非常简单:您需要将服务器配置为在获取路径/main(以及角度应用程序的所有其他路径)的请求时发回index.html页面。这样,浏览器将加载HTML页面,它包含的角度应用程序将重新启动,角度路由器将从URL解析路径(/main),因此它将加载视图和与之关联的控制器那道路。

相关问题