2014-01-09 37 views
0

我是Angular的新手,目前正在構建應用程序的身份驗證和導航部分。我遵循this有用的github條目中描述的想法。問題html5 pushstate in angularjs

當用戶導航到應用程序時,他們被重定向到<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'); 
      } 
     }); 

    }]); 

我缺少的東西?

回答

2

有兩件事你需要做到這一點。首先,您需要將您的Web服務器設置爲支持URL重寫。

對於Apache HTTP服務器.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); 

    [...] 

}]); 
+0

有誰知道如何支持Jetty的URL重寫?它只是一個過濾器? – Luke