XMLHttpRequest 无法加载:仅在 Ajax jQuery 中使用 headers

XMLHttpRequest cannot load : only with headers in Ajax jQuery

我尝试从我自己的 API 中获取 JSON 数据,使用 jQuery 的 $.ajax 方法。 我的请求中必须有一个 header 'Authorization-api-key' 否则我将有一个 401 状态代码。

$.ajax({
        type: "GET",
        headers: {'Authorization-api-key' : 'key'},
        dataType: "json",
        crossDomain: true,
        url: "http://urlofmyonlineapi.com/api/ressource",
        success: function (data) {
            alert(data);
        }
});

我在 Whosebug 上阅读了几个关于 CORS 和 'XMLHttpRequest cannot load' 问题的帖子。因此,在我的 API 中,我添加了这些 header 作为回应(我使用 Slim Framework):

$app->response->headers->set('Access-Control-Allow-Origin', '*');
$app->response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$app->response->headers->set('Access-Control-Allow-Headers', '*');
$app->response->headers->set('Access-Control-Allow-Credentials', 'true');

问题

如果我在 $.ajax 中放入任何 header 和 'headers: {...}' 参数,我的浏览器控制台会出现两个错误:

  1. 'OPTIONS'错误
  2. 'XMLHttpRequest cannot load'错误

如果我删除 headers,我没有错误,但我有 401 状态代码。 如果我使用请求的 header 中的密钥删除 header 和我的 API 的身份验证,我将获得我的数据。

我已经解决了问题:我的 API 没有接受 OPTIONS 请求。 (Ajax 和 jQuery 需要进行 OPTIONS 预请求)