无法使用jQuery发送CORS POST请求 [英] Unable to send a CORS POST request with jQuery

查看:446
本文介绍了无法使用jQuery发送CORS POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试通过ajax向单独的子域发送POST请求。预检请求(OPTIONS)已成功,但以下XMLHttpRequest请求将返回Origin http://app.example.com < a> is not allowed by Access-Control-Allow-Origin。

I'm trying to send a POST request to a separate subdomain via ajax. The preflight request (OPTIONS) is successful, but the following XMLHttpRequest request returns the "Origin http://app.example.com is not allowed by Access-Control-Allow-Origin."

客户端代码(app.example.com)如下所示:

The client side (app.example.com) code looks like this:

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)如下所示:

The server side code (api.example.com) looks like this:

$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状态。我希望有人能告诉我我失踪了。感谢!

The OPTIONS request returns a 200 status. I'm hoping someone is able to tell me what I'm missing. Thanks!

推荐答案

您需要:


  1. 完全移除 Access-Control-Allow-Credentials 标题(此请求不会发送任何Cookie),或:

  2. 将以下内容添加到您的ajax请求中: xhrFields:{withCredentials:true},

  1. Remove the Access-Control-Allow-Credentials header entirely (This will not send any cookies on the request), or:
  2. Add the following to your ajax request: xhrFields: { withCredentials: true },

第二个选项将包括请求的cookie。有关详情,请参阅此处: jQuery:发送带有跨域帖子的凭据? a>

The second option will include cookies on the request. See here for more details: jQuery: sending credentials with cross-domain posts?

您可能需要先尝试第一个选项,只是为了确保跨网域请求正常工作,然后添加Cookie(以使事情更容易调试)。

You might want to try the first option first, just to make sure the cross-domain request is working, and then add the cookies after that (to make things easier to debug).

这篇关于无法使用jQuery发送CORS POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆