【问题标题】:XmlHttpRequest with custom headers: Response for preflight doesn't pass access control check带有自定义标头的 XmlHttpRequest:预检响应未通过访问控制检查
【发布时间】:2017-03-10 11:30:08
【问题描述】:

我对 REST 服务器上的 ajax GET 请求有疑问。我做了一些测试,我会在这里发布。

在 REST 服务器中我有两种方法:

  • 1) resource_new_get(返回json数据,不需要自定义头部)
  • 2) resource_api_new_get(返回与第一个相同的 json 数据,但需要 Api-Key 自定义标头)

这是在服务器上执行 ajax 请求的 javascript 代码(在 resource_new_get 方法上):

app.updateResources = function(data)
  {
    if(data == null)
    {
      $.ajax(
      {
        url: 'http://<remotehost>/api/events/resource_new?id_event=<ID>',
        dataType: 'json',
        success: function(d)
        {
          console.log(d);
        },
        error: function(error)
        {
          console.log('error ' + JSON.stringify(error));
        }
      });
    }
    else
    {
      ...
    }
  };

在这种情况下,ajax 请求运行良好,我能够从服务器获取 json 响应。

但是当我向 resource_api_new 执行请求时,添加自定义标头如下:

app.updateResources = function(data)
{
if(data == null)
{
     $.ajax(
     {
           url: 'http://<remotehost>/api/events/resource_api_new?id_event=<ID>',
            dataType: 'json',
            headers: {'Api-Key': '<my_token>'},
            success: function(d)
            {
              console.log(d);
            },
            error: function(error)
            {
              console.log('error ' + JSON.stringify(error));
            }
          });
        }
        else
        {
          ...
        }
      };

这需要标头中的“Api-Key”键标识的令牌来返回 json 响应,错误函数触发并返回:

XMLHttpRequest cannot load http://<remotehost>/v2/index.php/api/events/resource_api_new?id_event=<ID>. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://<myhost>' is therefore not allowed access. The response had HTTP status code 404.

当我在包含 REST 服务器的 php 文件顶部添加以下行:

header('Access-Control-Allow-Origin: *');

响应返回“简单”的HTTP状态码404,如下:

XMLHttpRequest cannot load http://api.gtmasterclub.it/v2/index.php/api/eventi/relatori_api_new?id_evento=159. Response for preflight has invalid HTTP status code 404

【问题讨论】:

    标签: javascript php jquery json ajax


    【解决方案1】:

    我找到了问题的解决方案:

    Api-Key 标头未包含在 Access-Control-Allow-Headers 中,我简单地添加了以下内容:

    Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Api-Key
    

    另外,我添加了一个构造函数来处理 OPTIONS 请求,如下所述:

    HTTP OPTIONS error in Phil Sturgeon's Codeigniter Restserver and Backbone.js

    function __construct() {
            parent::__construct();
            $method = $_SERVER['REQUEST_METHOD'];
            if($method == "OPTIONS") {
                log_message('debug', 'method OPTIONS called');
                die();
            }
    }
    

    并且,在我删除的客户端脚本中:

    data-type: 'json',
    

    【讨论】:

      猜你喜欢
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 2016-06-05
      相关资源
      最近更新 更多