我想为我的应用启用 HTML5 模式。我已经放了如下代码进行配置,如图here :
return app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix = '!';
$routeProvider.when('/', {
templateUrl: '/views/index.html',
controller: 'indexCtrl'
});
$routeProvider.when('/about',{
templateUrl: '/views/about.html',
controller: 'AboutCtrl'
});
如您所见,我使用了 $locationProvider.html5mode
并更改了 ng-href
处的所有链接以排除 /#/
。
目前,我可以转到 localhost:9000/
并查看索引页面并导航到其他页面,例如 localhost:9000/about
。
但是,当我刷新 localhost:9000/about
页面时会出现问题。我得到以下输出: Cannot GET/about
如果我查看网络调用:
Request URL:localhost:9000/about
Request Method:GET
如果我先去 localhost:9000/
然后点击导航到 /about
的按钮,我会得到:
Request URL:http://localhost:9000/views/about.html
完美呈现页面。
如何在刷新时启用 Angular 以获取正确的页面?
最佳答案
来自 angular docs
Server side
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)
原因是当您第一次访问页面时(/about
),例如刷新后,浏览器无法知道这不是一个真实的 URL,因此它会继续加载它。但是,如果您首先加载了根页面和所有 javascript 代码,那么当您导航到 /about
时,Angular 可以在浏览器尝试访问服务器并相应地处理它之前进入那里
关于angularjs - 使用 AngularJS HTML5 模式重新加载页面会给出错误的 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16569841/