【问题标题】:Routing is not working in my web application when I refresh the page in the browser当我在浏览器中刷新页面时,路由在我的 Web 应用程序中不起作用
【发布时间】:2016-07-14 14:22:33
【问题描述】:

当我在浏览器中输入http://localhost:8000 时,它会重定向到http://localhost:8000/home。根据代码,这工作正常。当我用相同的http://localhost:8000/home 刷新页面时出现 404 错误。谁能帮助我为什么会发生这种情况并纠正我。

app.js

var myapp=angular
            .module("demo",['ngRoute'])
            .config(function ($routeProvider, $locationProvider){
              $routeProvider
              .when('/home',{
                templateUrl:'Templates/home.html',
                controller:'homeController'
              })
              .when('/about', {
                templateUrl:'Templates/about.html',
                controller:'aboutController'
              })
              .when('/contact',{
                templateUrl:'Templates/contact.html',
                controller:'contactController'
              })

              .otherwise({
               redirectTo: '/home'
               })
              $locationProvider.html5Mode(true);
            });

index.html

<!doctype html>
<html lang="en" ng-app="demo">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
     <script src="bower_components/angular/angular.js"></script>
     <script src="bower_components/angular-route/angular-route.js"></script>
     <script src="rest-controller.component.js"></script>
     <script src="Controllers/contact.js"></script>
     <script src="Controllers/about.js"></script>
     <script src="Controllers/home.js"></script>
     <base href="/">
</head>
<body>
   <ol>
    <li><a href="home">Home</a></li>
    <li><a href="about">About</a></li>
    <li><a href="contact">Contact</a></li>
  </ol>
  <div ng-view></div>
</body>
</html>

home.js(控制器文件)

 angular.module('demo').controller("homeController", function($scope){
   $scope.hello ="home";
  });

关于.js

angular.module('demo').controller("aboutController", function($scope){
  $scope.tap="About Me";
 });

contact.js

angular.module('demo').controller("contactController", function($scope){
 $scope.message="hello";
});

【问题讨论】:

  • 404错误是服务器服务的吗?
  • 不能在不配置服务器的情况下随意使用html5Mode。您的服务器对正在使用的虚拟目录一无所知。见docs.angularjs.org/guide/$location
  • 服务器也需要配置。它现在的工作方式是在初始请求时从服务器加载站点。当您更改路线时,这是在客户端完成的。然后,如果您刷新页面,它会向服务器请求新路由,但服务器不知道它。
  • 是的,它仅来自服务器@Arun Ghosh
  • @sir 你的应用服务器堆栈是什么?

标签: javascript angularjs html routing


【解决方案1】:

您可以尝试禁用 html5 模式吗?

// $locationProvider.html5Mode(true);

【讨论】:

  • @sri:禁用后转到localhost:8000,何时单击主页应该转到localhost:8000/#/home。 # 来了吗?
  • 禁用 html5 模式后,我在浏览器中输入 localhost:8000,它重定向到 localhost:8000/#/home。这是有效的
  • 我使用 ui-router 而不是 ng-router 然后它工作正常。现在,每当您刷新页面时,我都可以看到与 url 相对应的确切视图。
猜你喜欢
  • 2020-12-02
  • 1970-01-01
  • 2022-08-17
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多