php - 无法使用 jQuery 发送 CORS POST 请求

标签 php jquery http cors

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

客户端 (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 状态。我希望有人能够告诉我我错过了什么。谢谢!

最佳答案

您需要:

  1. 完全删除 Access-Control-Allow-Credentials header (这不会根据请求发送任何 cookie),或者:
  2. 将以下内容添加到您的 ajax 请求中:xhrFields: { withCredentials: true },

第二个选项将在请求中包含 cookie。有关更多详细信息,请参见此处:Sending credentials with cross-domain posts?

您可能想先尝试第一个选项,只是为了确保跨域请求正常工作,然后再添加 cookie(以便于调试)。

关于php - 无法使用 jQuery 发送 CORS POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15513084/

相关文章:

php - 使用来自 mysql 的元键获取元值

javascript - Jquery,如何拆分()字符串并在中间获取目标字符串?例如 : sample_str[targeted_str][other_str]

php - 缩小 HTML/PHP

PhpMyAdmin 自动刷新 MySQL 表

javascript - JSON 对象(如何最初不将整个对象加载到 DOM 上)

javascript - IE 9 中 FileReader() 的垫片

HTTP文件服务器: Single file,跨平台,拖放启动

Python HTTP 错误 403 禁止访问

http - 如何构建 Firefox 扩展来拦截 HTTP 请求和响应?

php - 只检查第一条记录,而不是所有