CORS:无法获取POST请求正文。

问题描述 投票:0回答:2

我正在尝试使用XMLHttpRequest从file://example.html到http://localhost/index.php发出请求。我读了很多关于CORS的内容(在这种情况下,起源是空的,这没关系。)我不知道我做错了什么。我的请求很好,但$ _POST是空的!除非我设置“Content-type:application / x-www-form-urlencoded”。但是“text / plain”或“application / json”没有给$ _POST带来任何结果......为什么?

    xhr.open("POST", "http://localhost/index.php", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onreadystatechange = handler;
    xhr.send({'a':'12'});
javascript php cors
2个回答
4
投票

您可能正在做以下两件事之一:

如果content-type不是application/x-www-form-urlencoded,则CORS必须发送预检请求。这意味着浏览器将在POST请求之前发送OPTIONS请求,该请求用于确定是否允许POST请求。看看here这是如何工作的。

其次,如果你使用xhr.setRequestHeader("Content-Type", "application/json")$_POST参数将不会填充参数,这只是application / x-www-form-urlencoded的情况。要获得您发送的JSON,您必须执行以下操作:

<?php
  $input = json_decode(file_get_contents("php://input"), true);
  echo $input['a']; //echoes: 12

有关更多信息,请参阅this问题。

此外,如果您进入任何体面浏览器的调试工具,如果不允许CORS请求,它将创建一条错误消息,请务必检查CORS请求是否实际上是由浏览器发出的。

我希望这可以帮助你。


1
投票

补充@ user23127响应

服务器端应该有类似的东西来响应OPTIONS预检请求:

if (request.method === 'OPTIONS') {
  htmlRes = HttpResponse()
  htmlRes['Access-Control-Allow-Origin']='*' // or your not origin domain
  htmlRes['Access-Control-Allow-Methods']='*' // or POST, GET, PUT, DELETE
  htmlRes['Access-Control-Allow-Headers']='*' // Content-Type, X-REQUEST
}
// the rest of the code as if it was not a CORS request
© www.soinside.com 2019 - 2024. All rights reserved.