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

Joh*_*ohn 1 javascript php cors

我正在尝试使用 XMLHttpRequest 从 file://example.html 到http://localhost/index.php发出请求。我读了很多关于 CORS(在这种情况下,origin 为 null,这是可以的。)我不知道我做错了什么。我的请求完成得很好,但 $_POST 是空的!除非我设置了“内容类型:应用程序/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'});
Run Code Online (Sandbox Code Playgroud)

use*_*127 5

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

如果内容类型不是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
Run Code Online (Sandbox Code Playgroud)

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

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

我希望这可以帮助你。