AJAX如何在标头中传递api密钥

pri*_*nce 4 javascript ajax jquery json

我在这里遇到 AJAX 调用的奇怪情况,如何在标头中传递 api 密钥:

我的 json 的完整网址是:https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&APIkey=fd6b8ec7d651960788351ee2b1baffba6ac1a9c8eb047118a1a823c247bdade0 我现在尝试在 ajax 调用的标头中传递 API 密钥,但控制台仍然出现此错误:

“无法加载https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&:对预检请求的响应未通过访问控制检查:否“Access-Control-Allow” -Origin'标头存在于请求的资源上。因此不允许访问Origin'http: //bigsportlive.com '。” 这是我的 ajax 调用:

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
    }
 });
Run Code Online (Sandbox Code Playgroud)

也许我做的事情不正确?谢谢!

Ami*_*UIS 5

如果要向每个请求添加一个标头(或一组标头),请使用$.ajaxSetup ()的beforeSend钩子:

$.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' } });
Run Code Online (Sandbox Code Playgroud)

另一个解决方案包括使用小写字母作为标题

$(document).ready(function () {
        $.ajax({
            url: "http://xx.xx.xx.xx:xx/api/values",
            type: "GET",
            dataType: "json",
            headers: { "HeaderName": "MYKey" }
        });
    });
Run Code Online (Sandbox Code Playgroud)