3

I have here a strange situation with AJAX call, how to pass api key in header:

My full url for my json is: https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&APIkey=fd6b8ec7d651960788351ee2b1baffba6ac1a9c8eb047118a1a823c247bdade0 And I am trying now to pass API key in headers of ajax call, but still have this error from console:

"Failed to load https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://bigsportlive.com' is therefore not allowed access." Here is my ajax call:

var apiKey = "fd6b8ec7d651960788351ee2b1baffba6ac1a9c8eb047118a1a823c247bdade0";
$.ajax({
    type: "GET",
    url: "https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01",
    headers: { "APIkey": apiKey },
    success: function(result){
      result[i].league_name
    }
 });

May be I am doing something not correct? Thanks!

prince
  • 449
  • 2
  • 5
  • 6
  • it's a CORS issue, nothing to do with API key ... `apifootball.com` **doesn't allow** calls from a **browser** only another **server** – Jaromanda X Nov 01 '17 at 01:08
  • or perhaps you should read their API documentation which states you add the API key to the URL - `&APIkey=xxxxxxxxxxxxxx` - nowhere in their documentation does it state you should use the APIkey in any headers – Jaromanda X Nov 01 '17 at 01:10

2 Answers2

4

If you want to add a header (or a set of headers) to each request, use the beforeSend hook with $.ajaxSetup ():

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('x-my-custom-header', 'some value');
    }
});

// Sends your custom header
$.ajax({ url: 'your/url' });

// Sends both custom headers
$.ajax({ url: 'your/url', headers: { 'x-some-other-header': 'some value' } });

Another solution consist to use lowercase for headers

$(document).ready(function () {
        $.ajax({
            url: "http://xx.xx.xx.xx:xx/api/values",
            type: "GET",
            dataType: "json",
            headers: { "HeaderName": "MYKey" }
        });
    });
Amine KOUIS
  • 1,686
  • 11
  • 12
0

Yes, there is an Access-Control-Allow-Origin error. If so, you may want a php backend to get this for you, I believe, using

<?php
    $data = file_get_contents("https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&APIkey=fd6b8ec7d651960788351ee2b1baffba6ac1a9c8eb047118a1a823c247bdade0");

echo json_encode($data);
?>

Then use an ajax call to this file.

$.ajax({
            type: "GET",
            url: 'name_of_php_file.php',
            dataType: "json",
            success: function(result){
              alert(result);
            }
        });
Fruckubus Crunt
  • 199
  • 2
  • 16