CORS:无法获取POST请求正文


CORS: Can't get POST request body.

我正试图从file://example.html到http://localhost/index.php使用XMLHttpRequest请求。我读了很多关于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'});

你可能做错了以下两件事之一:

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

其次,如果您使用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

更多信息请参见这个问题。

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

补充@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