How to send an HTTP request with a header parameter?

前端 未结 2 764
花落未央
花落未央 2021-02-02 00:26

I\'m very new to javascript and web programming in general and I need some help with this. I have an HTTP request that I need to send through javascript and get need to store th

相关标签:
2条回答
  • 2021-02-02 01:14

    If it says the API key is listed as a header, more than likely you need to set it in the headers option of your http request. Normally something like this :

    headers: {'Authorization': '[your API key]'}
    

    Here is an example from another Question

    $http({method: 'GET', url: '[the-target-url]', headers: {
      'Authorization': '[your-api-key]'}
    });
    

    Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :

    $.ajax({ 
       type : "GET", 
       url : "[the-target-url]", 
       beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
       success : function(result) { 
           //set your variable to the result 
       }, 
       error : function(result) { 
         //handle the error 
       } 
     }); 
    

    I got this from this question and I'm at work so I can't test it at the moment but looks solid

    Edit 2: Pretty sure you should be able to use this line :

    headers: {'Authorization': '[your API key]'},
    

    instead of the beforeSend line in the first edit. This may be simpler for you

    0 讨论(0)
  • 2021-02-02 01:18

    With your own Code and a Slight Change withou jQuery,

    function testingAPI(){ 
        var key = "8a1c6a354c884c658ff29a8636fd7c18"; 
        var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
        console.log(httpGet(url,key)); 
    }
    
    
    function httpGet(url,key){
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", url, false );
        xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
        xmlHttp.send(null);
        return xmlHttp.responseText;
    }
    

    Thank You

    0 讨论(0)
提交回复
热议问题