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

问题描述

限时删除!!

我想使用 Angular.js 在单页 Web 应用程序上实现身份验证.官方 Angular 文档 推荐使用拦截器:

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 标头时),但 Angular 无法用它捕获按照建议拦截要处理的 HTTP 错误.我误解了什么吗?我尝试了在网上找到的更多示例(thisthisthis 例如),但它们都不起作用.

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);
  }
}];

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

1403页,肝出来的..

09-06 15:55