如何通过身份验证生成$ http?

时间:2015-09-21 13:13:09

标签: angularjs

我已向API发出POST请求并且他们有基本身份验证,如何在发出请求时告诉angular $ http POST服务传递我的凭据?

1 个答案:

答案 0 :(得分:3)

您可以按如下方式添加auth拦截器

angular.module('interceptors.authInterceptor',[])

.factory('authInterceptor', ['$q', function ( $q) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      config.headers['Authorization'] = 'Bearer ' + YOUR_AUTH_TOKEN;
      return config;
    },
    response: function (response) {
      return response || $q.when(response);
    },
    responseError: function(rejection) {
    }    

  };
}])

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