corspost请求失败_无法使用jQuery发送CORS POST请求

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."

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);

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');

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

解决方案

You need to either:

Remove the Access-Control-Allow-Credentials header entirely (This will not send any cookies on the request), or:

Add the following to your ajax request: xhrFields: { withCredentials: true },

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

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).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值