如何使用angularjs和laravel将用户重定向到登录页面

时间:2014-11-13 05:04:10

标签: angularjs laravel

我正在使用laravel和angularjs开展项目。我只使用Laravel来验证用户,当他们登录时,angularjs ui veiw将处理导航。当我这样做时,我意识到一个问题,当会话到期时,应该根据路由上设置的auth过滤器将用户重定向到登录页面。此外,当我检查浏览器开发工具网络选项卡时,我看到登录页面是作为响应发送的。我想知道如何在会话到期时让我的项目将用户重定向到登录页面。我该如何解决这个问题,并提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

你可以用$ httpInterceptor做到这一点,这里是演示代码:

var myApp = angular.module("MyApp", []);
myApp.config(function ($httpProvider, $provide) {
    $provide.factory('myHttpInterceptor', function ($q, $location) {
        return {
            'response': function (response) {
                //you can handle you sucess response here.
                return response;
            },
            'responseError': function (rejection) {
                console.log(rejection);
                //if(rejection.data.xxx==="xxx")
                if(rejection.status === 408){//session expired code
                    alert('logout!');
                    // clear your local data here...
                    $location.url("/login")
                }
                return $q.reject(rejection);
            }
        };
    });
    $httpProvider.interceptors.push('myHttpInterceptor');
});
myApp.controller("MainController", function ($scope, $http) {
    $scope.response = {};
    $scope.triggerGet = function () {
        $http.get("/my/json").success(function (data) {
            $scope.response = data;
        });
    };
});

当您的服务器端响应会话已过期时,您可以处理response.status,或者您可以使用response.data处理其他数据。

Here is $httpInterceptor document.(In the middle of the page)

答案 1 :(得分:0)

要在JavaScript中使用location重定向用户客户端。 https://developer.mozilla.org/en-US/docs/Web/API/Location

对于这种情况,我想你想具体看一下location.assign()

相关问题