[javascript] How to send an HTTP request with a header parameter?

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 the output in a variable. I tried using just the call url:

https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015

But it returns an authentication error because I didn't send my API key and it doesn't show me how to do it just in the URL. The API key is listed as a header and not a paramater and I'm not sure what to do with that. I tried using the XMLHttpRequest() class but I'm not quite sure I understand exactly what it does nor could I get it to work.

The actual HTTP Request

GET https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015 HTTP/1.1
Host: api.fantasydata.net
Ocp-Apim-Subscription-Key: ••••••••••••••••••••••••••••••••

I just need to figure out how to send that request along with the key and how to store the JSON doc it returns as a variable in javascript.

EDIT: This is what I have so far:

function testingAPI(){
var key = "8a1c6a354c884c658ff29a8636fd7c18";
httpGet("https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015",key    );
alert(xmlHttp.responseText);
var x = 0;
}

function httpGet(theUrl,key)
{
var xmlHttp = new XMLHttpRequest();

xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
xmlHttp.send( null );
return xmlHttp.responseText;
}

Thank you!

This question is related to javascript json api http callback

The answer is


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


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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to api

I am receiving warning in Facebook Application using PHP SDK Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Failed to load resource: the server responded with a status of 404 (Not Found) css Call another rest api from my server in Spring-Boot How to send custom headers with requests in Swagger UI? This page didn't load Google Maps correctly. See the JavaScript console for technical details How can I send a Firebase Cloud Messaging notification without use the Firebase Console? Allow Access-Control-Allow-Origin header using HTML5 fetch API How to send an HTTP request with a header parameter? Laravel 5.1 API Enable Cors

Examples related to http

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe

Examples related to callback

When to use React setState callback How to send an HTTP request with a header parameter? javascript function wait until another function to finish What is the purpose of willSet and didSet in Swift? How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()? Aren't promises just callbacks? How do I convert an existing callback API to promises? How to access the correct `this` inside a callback? nodeJs callbacks simple example Callback after all asynchronous forEach callbacks are completed