[英]issues with html 5 pushstate in angularjs
我是Angular的新手,目前正在构建应用程序的身份验证+导航部分。 我遵循了这个有用的github条目中描述的想法。
当用户导航到应用程序时,他们会被重定向到<app>/login
,正确显示登录屏幕。
我的问题是,在我的实现中,与教程不同,当用户将URL设置为<app>/login
我得到404而不是正确的页面( <app>/#/login
运行良好)。
我正在使用AngularJS v1.2.5,这是我的应用程序配置文件:
'use strict';
angular.module('myApp', ['ngCookies', 'ngRoute', 'ngResource'])
.config(['$routeProvider', '$locationProvider', '$httpProvider',
function ($routeProvider, $locationProvider, $httpProvider) {
var access = routingConfig.accessLevels;
$routeProvider.when('/',
{
templateUrl: 'views/home.html',
controller: 'HomeCtrl',
access: access.anon
});
$routeProvider.when('/login',
{
templateUrl: 'views/login.html',
controller: 'HomeCtrl',
access: access.anon
});
$routeProvider.when('/404',
{
templateUrl: 'views/404.html',
access: access.anon
});
$routeProvider.otherwise({redirectTo: '/404'});
$locationProvider.html5Mode(true);
$httpProvider.interceptors.push(function ($q, $location) {
return {
'responseError': function (response) {
if (response.status === 401 || response.status === 403) {
$location.path('/login');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
}
});
}])
.run(['$rootScope', '$location', '$http', 'Auth', function ($rootScope, $location, $http, Auth) {
$rootScope.$on("$routeChangeStart", function (event, next, current) {
$rootScope.error = null;
if (!Auth.authorize(next.access)) {
if(Auth.isLoggedIn()) $location.path('/');
else $location.path('/login');
}
else {
angular.element('body').removeClass('naked');
}
});
}]);
我错过了什么吗?
完成此任务需要两件事。 首先,您需要设置Web服务器以支持URL重写。
对于Apache HTTP Server,将.htaccess
添加到您网站的根目录并包含此代码段。 如果文件尚不存在,它会将所有URL重定向到index.html
。
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
其次,您已经拥有的是在AngularJS模块的配置中添加$locationProvider.html5Mode(true)
。 Angular Doc:$ location
.config(['$routeProvider', '$locationProvider', '$httpProvider',
function ($routeProvider, $locationProvider, $httpProvider) {
$locationProvider.html5Mode(true);
[...]
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.