我正在尝试通过ajax将POST请求发送到单独的子域。预检请求(OPTIONS)成功,但以下XMLHttpRequest请求返回Access-Control-Allow-Origin不允许“Origin http://app.example.com。”
客户端(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');
OPTIONS请求返回200状态。我希望有人能告诉我我错过了什么。谢谢!
答案 0 :(得分:1)
您需要:
Access-Control-Allow-Credentials
标题(这不会在请求中发送任何Cookie),或者:xhrFields: { withCredentials: true },
第二个选项将包括请求中的cookie。有关详情,请参阅此处:Sending credentials with cross-domain posts?
您可能希望首先尝试第一个选项,只是为了确保跨域请求正常工作,然后在此之后添加cookie(以便更容易调试)。