2017-03-10 26 views
2

我在REST服務器上發出ajax GET請求時出現問題。我做了一些測試,我會在這裏發佈。帶自定義標題的XmlHttpRequest:針對預檢的響應未通過訪問控制檢查

在REST服務器我兩種方法:

  • 1)resource_new_get(返回JSON數據和不需要自定義首部)
  • 2) resource_api_new_get(resurns相同JSON數據作爲第一,但需要一個API-密鑰自定義首部)

這是執行服務器上的AJAX請求(在resource_new_get方法的JavaScript代碼):

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的關鍵」的標題鍵返回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. 

當我在PHP文件的頂部,它包含REST服務器,添加以下行:

頭('訪問控制-A llow-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 

回答

0

,我發現這個問題的解決:

的API-Key標頭不包括在接入控制 - 允許-header和我加入簡單:

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', 
相關問題