Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX how to pass api key in header [duplicate]

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!

like image 598
prince Avatar asked Oct 29 '25 17:10

prince


1 Answers

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" }
        });
    });
like image 108
Amine KOUIS Avatar answered Oct 31 '25 07:10

Amine KOUIS