最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Log out if status code is 403 in angularjs - Stack Overflow

programmeradmin0浏览0评论

I have a SPA(single page application), and it sends a lot of http requests to a server and the server checks whether the user who is sending the request is authenticated or not.

If the user is not authenticated, I redirect him to a login page like this:

$scope.getGroups = function () {
    $http({
        method: "get",
        url: "/enterprises/groups"
    }).success(function (response) {
        GroupService.updateGroups(response.groups);
    }).error(function (errResponse, status) {
        if(status == 403){
            $location.path("login")
        }
    });
};

The problem is that I have a lot of http requests and I don't want to handle the "forbidden" exception every time.

Is there any way to write this kind of code in, let's say, config and apply it everywhere?

I have a SPA(single page application), and it sends a lot of http requests to a server and the server checks whether the user who is sending the request is authenticated or not.

If the user is not authenticated, I redirect him to a login page like this:

$scope.getGroups = function () {
    $http({
        method: "get",
        url: "/enterprises/groups"
    }).success(function (response) {
        GroupService.updateGroups(response.groups);
    }).error(function (errResponse, status) {
        if(status == 403){
            $location.path("login")
        }
    });
};

The problem is that I have a lot of http requests and I don't want to handle the "forbidden" exception every time.

Is there any way to write this kind of code in, let's say, config and apply it everywhere?

Share Improve this question asked Feb 3, 2015 at 11:50 Jahongir RahmonovJahongir Rahmonov 13.8k10 gold badges51 silver badges99 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

You can create a service to handle this and add it to the $http interceptors. As service like below:

app.factory('authInterceptorService', ['$q','$location', function ($q, $location){
    var responseError = function (rejection) {
        if (rejection.status === 403) {
            $location.path('login');
        }
        return $q.reject(rejection);
    };

    return {
        responseError: responseError
    };
}]);

Then add this to the in config

app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('authInterceptorService');
}]);

This would then be applied to all requests made.

I came across needing to the same in my own app very recently and ended up using an interceptor on the $httpProvider. This sort of thing:

angular.module('notesApp', [])
  .controller('MainCtrl', ['$http', function($http) {
    ...

  }]).factory('MyLoggingInterceptor', ['$q', function($q) {
    return {
      request: function(config) {
        console.log('Request made with ', config);
        return config;
        // If an error, or not allowed, or my custom condition
        // return $q.reject('Not allowed');
      },
      requestError: function(rejection) {
        console.log('Request error due to ', rejection);
        // Continue to ensure that the next promise chain
        // sees an error
        return $q.reject(rejection);
        // Or handled successfully?
        // return someValue;
      },
      response: function(response) {
        console.log('Response from server', response);
        // Return a promise
        return response || $q.when(response);
      },
      responseError: function(rejection) {
        console.log('Error in response ', rejection);
        // Continue to ensure that the next promise chain
        // sees an error
        // Can check auth status code here if need to
        // if (rejection.status === 403) {
        //   Show a login dialog
        //   return a value to tell controllers it has
        // been handled
        // }
        // Or return a rejection to continue the
        // promise failure chain
        return $q.reject(rejection);
      }
    };
  }])
  .config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('MyLoggingInterceptor');
  }]);
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>