2016-07-28 56 views
0

我正在使用angularjs ngRoute来路由单个页面应用程序。它显示了localhost/about或localhost/blog。 当我reaload,“无法GET/about”。我怎样才能解决这个问题。在ngRoute中刷新页面时找不到页面

我的路由器配置如下。

var myApp = angular.module('myApp',['ngRoute']); 
myApp.config(['$locationProvider','$routeProvider',function($locationProvider,$routeProvider){ 
    $locationProvider.html5Mode(true); 
    $routeProvider 
     .when('/',{ 
      templateUrl: 'views/pages/home.html', 
      controller: 'homeCtrl' 
     }) 
     .when('/about',{ 
      templateUrl: 'views/pages/about.html', 
      controller: 'aboutCtrl' 
     }) 
     .when('/contact',{ 
      templateUrl: 'views/pages/contact.html', 
      controller: 'contactCtrl' 
     }) 
     .when('/blog',{ 
      templateUrl: 'views/pages/blog.html', 
      controller: 'blogCtrl' 
     }) 
     .otherwise({redirectTo: '/home'}); 
    }]); 

我只使用角度。

+0

您的后端需要捕获所有请求并为您的Angular应用程序提供服务。 – str

+0

正如你所说的“我只使用角度”,那么你能提供一个JSFiddel或Plunker的例子,你的代码不工作? –

回答

0

这是因为这段代码

$locationProvider.html5Mode(true); 

设置它false将在每个网址的开头加上#的,因此服务器会给你的索引页不管你重装的页面。

+0

我的网页网址必须显示没有#标签,有没有其他方式来路由页面没有#标签的角度。 – Sathish

0

您可能正在使用服务器路由,而不是AngularJS路由。 AngularJS默认使用#之后的路由来路由网址。例如http://localhost:8080/#/about

此外,您可以使用HTML5路由与$locationProvider.html5Mode(true)其中使用我认为你使用的路由http://localhost:8080/about

+0

是的,我使用$ locationProvider.html5Mode(true),用于显示像http:// localhost:8080/about这样的url。我想要的是同样的东西,它不会显示#标签。有没有其他的方式来加载html5模式的页面true。 – Sathish

+0

您能提供有关错误的更多信息吗?浏览器版本,Plunker复制该问题......查看http://caniuse.com/#search=history以查看兼容的浏览器。 – Ruben

+0

请检查网址http://sathishstar.netai.net/home – Sathish

0

有关AngularJS路由的文档不是很清楚。它讨论了Hashbang和HTML5模式。事实上,AngularJS路由三种工作模式:

  • Hashbang模式
  • HTML5模式
  • Hashbang在HTML5模式

这是因为您使用的是不支持HTML5模式的浏览器。正如上面提到的@Mumpo。

你应该改变这一行

$locationProvider.html5Mode(true); 

这一行

$locationProvider.html5Mode(false); 

这将使Hashbang模式和你的网址

如需进一步前会在前面加上#号深入了解这三种模式。请参考Stackoverflow问题here。希望这会有所帮助

+0

其实我想要html5模式。我希望网址能像这样http://www.example.com/base/path显示。不使用hasbang方法,我可以加载页面。 – Sathish

+0

我们的三个应用程序实际上使用了Hashbang模式。然而,在我们想要使用漂亮的URL的地方,我们在这些项目中使用了MVC和AngularJs。我们使用MVC路由处理路由,以显示诸如** example.com/base/path **和其他通过AngularJs工作的URL。如果你想使用MVC,我可以与你分享这个逻辑 –

+0

至于只使用AngularJs,请看这个[link](https://scotch.io/tutorials/pretty-urls-in-angularjs-removing-the-hashtag)它可能会帮助你。您只需要定义所有路线并添加基础网址。希望它会有所帮助 –