【问题标题】:Angular JS passes App ID and Key with every requestAngular JS 在每个请求中传递 App ID 和 Key
【发布时间】:2017-06-23 19:30:14
【问题描述】:

我有一个基本的 Angular 应用程序,它可以对 API URL 进行 GET 请求调用。返回的数据为 JSON 格式。 API 文档声明如下:

您必须在向 API 发出的每个请求中提供您的 App ID 和密钥。为此,请在您的请求中设置一个 HTTP 授权标头,该标头由您的 ID、后跟一个冒号和您的密钥组成,例如 abc123:xyz789。

如何将其合并到我的基本 HTTP 请求中。我的代码如下。

angular.module('myApp', [])
.controller('MyControler', function($scope, $http) {
  $scope.$watch('search', function() {
    fetch();
  });

   $scope.search = "My Search Query";

   function fetch() {
   $http.get("https://APIURlGoesHere" + $scope.search )
    .then(function(response) {
      $scope.details = response.data;
    });

  $http.get("ttps://APIURlGoesHere" + $scope.search)
    .then(function(response) {
      $scope.related = response.data;
    });
  }

});

【问题讨论】:

    标签: javascript jquery angularjs angularjs-scope


    【解决方案1】:

    目前我知道的最好的实现方式是:拦截器

    你可以在herehere找到一些有用的信息

    然后,在这里:AngularJS $http interceptors

    在您的情况下,基本上,您需要创建一个具有以下实现(或等效)的文件并将其包含到您的项目中:

    function myInterceptor() {
    
        function request(req) {
    
            var token = "mytoken" ;  //<<--here you need to set the custom header's info (eg: abc123:xyz789)
            var myHeader = "myHeader";  //<<--here you need to set the custom header's name (eg: Authorization)
    
            if (token) {
                //put custom header for sending the token along with every request
                req.headers[myHeader] = token;
            }
    
            return req;
        }
    
        return {
            request: request
        };
    
    };
    
    function conf($httpProvider) {
        $httpProvider['interceptors'].push('myInterceptor');
    };
    
    angular
        .module('your_module_name')
        .factory('myInterceptor', myInterceptor)
        .config(['$httpProvider', conf]);
    

    这将拦截从您的前端应用发出的每个请求,并将在其上包含该标头。

    【讨论】:

    • 这看起来很棒,我会测试一下并回复你。谢谢
    • 当然可以。我用过很多次。它就像魅力;)
    • 是的。角 1.
    【解决方案2】:

    引用这个话题:

    How to use Basic Auth with jQuery and AJAX?

    因此,在 Angular 中,它将是:

    $http({
          method: "GET",
          url: "https://APIURlGoesHere" + $scope.search,
         headers: { 'Authorization' : 'Basic '+btoa(username + ":" + password) 
         })
    .then(function(response) {
      $scope.details = response.data;
    });
    

    【讨论】:

    • 这种方法有一个不便之处:在实现的每个服务调用上都需要以这种方式设置标头。例如:如果接收标头的方式由您的 api 提供程序更改(不是很常见,但它可能发生),您必须在项目的每个文件上更改此实现,标头设置为这种方式(可以是千)。不是很好。
    猜你喜欢
    • 2021-02-16
    • 2011-12-22
    • 1970-01-01
    • 2017-01-06
    • 2018-05-30
    • 2014-03-17
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多