2013-03-20 94 views
1

我想通過ajax發送一個POST請求到一個單獨的子域。預檢請求(OPTIONS)成功,但以下XMLHttpRequest請求返回「來源http://app.example.com不被Access-Control-Allow-Origin允許」。無法發送與jQuery的CORS POST請求

客戶端側(app.example.com)代碼看起來是這樣的:

var settings = { 
    url: 'http://api.example.com/auth', 
    type: 'POST', 
    contentType: 'application/json', 
    crossDomain: true, 
    headers: {"X-Requested-With": "XMLHttpRequest"}, 
    username: data.username, 
    success: callback, 
    error: callback 
}; 

$.ajax(settings); 

服務器端代碼(api.example.com)看起來像這樣:

$this->output->set_header('Content-Type: application/json; charset=utf-8'); 
$this->output->set_header('Access-Control-Allow-Origin: http://app.example.com'); 
$this->output->set_header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS'); 
$this->output->set_header('Access-Control-Allow-Headers: X-Requested-With, Origin, X-Csrftoken, Content-Type, Accept'); 
$this->output->set_header('Access-Control-Allow-Credentials: true'); 

的選項請求返回200狀態。我希望有人能夠告訴我我錯過了什麼。謝謝!

回答

1

您需要:

  1. 完全卸下Access-Control-Allow-Credentials頭(這將不會發送該請求的任何cookie),或:
  2. 以下內容添加到您的Ajax請求:​​

第二個選項將包含請求中的cookie。請參閱此處以瞭解更多詳細信息:Sending credentials with cross-domain posts?

您可能想首先嚐試第一個選項,以確保跨域請求正常工作,然後在此之後添加cookie(使事情更易於調試)。