捕获HTTP 401 Angular.js拦截 [英] Capture HTTP 401 with Angular.js interceptor

查看:1221
本文介绍了捕获HTTP 401 Angular.js拦截的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想与Angular.js单个页面的Web应用程序实现身份验证。该官方角文档建议使用拦截器:

I'd like to implement authentication on a single page web app with Angular.js. The official Angular documentation recommends the using of interceptors:

$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {

    // ...

    'responseError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise
      }
      return $q.reject(rejection);
    }
  };
});

在服务器发送401错误的问题是,浏览器会立即停止用未授权的消息,或登录弹出窗口(当认证HTTP报头由服务器发送),但角度不能捕捉与它的拦截HTTP错误处理,因为建议。我误解的东西吗?我试图在网络上找到的更多例子(<一个href=\"http://www.frederiknakstad.com/authentication-in-single-page-applications-with-angular-js/\">this, <一href=\"http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app\">this和这个为例),但他们没有工作。

The problem is when the server sends 401 error, the browser immediately stops with "Unauthorized" message, or with login pop-up window (when authentication HTTP header is sent by the server), but Angular can't capture with it's interceptor the HTTP error to handle, as recommended. Am I misunderstanding something? I tried more examples found on web (this, this and this for example), but none of them worked.

推荐答案

在应用程序配置块:

var interceptor = ['$rootScope', '$q', "Base64", function (scope, $q, Base64) {
        function success(response) {
            return response;
        }
        function error(response) {
            var status = response.status;
            if (status == 401) {
                //AuthFactory.clearUser();
                window.location = "/account/login?redirectUrl=" + Base64.encode(document.URL);
                return;
            }
            // otherwise
            return $q.reject(response);
        }
        return function (promise) {
            return promise.then(success, error);
        }
    }];

这篇关于捕获HTTP 401 Angular.js拦截的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆