$ _POST没有从Javascript的Fetch()中检索数据

dit*_*tto 11 javascript php post

我正在使用javascript发布数据fetch().

    fetch('/string.php', {
      method: 'post',
      body: JSON.stringify({
        name: 'helloe world',
      })
    })
    .then(function(response) {
      if (response.status >= 200 && response.status < 300) {
        return response.text()
      }
      throw new Error(response.statusText)
    })
    .then(function(response) {
      console.log(response);
    })
Run Code Online (Sandbox Code Playgroud)

string.php文件包含:

print_r($_POST);
Run Code Online (Sandbox Code Playgroud)

现在我的问题是$_POST返回一个空数组.我可以通过附加文件来解决这个问题:

$_POST = json_decode(file_get_contents('php://input'), true);
Run Code Online (Sandbox Code Playgroud)

但这感觉非常苛刻,并不理想.这是从JS检索发布数据时PHP的预期行为fetch()吗?

反正我是否可以自动将内容放入$_POST

Nie*_*sol 17

$_POST仅填充application/x-www-form-urlencodedmultipart/form-data请求.

对于任何其他数据格式,您需要php://input手动解析.在您的情况下,您正在使用json_decode并将结果放在$_POST超全局中,这是将JSON"转换"为表单数据的可接受方式.


Que*_*tin 5

但这感觉非常hackish,并不理想。

分配给$_POST有点奇怪。它通常被视为只读。大多数人会使用另一个变量。

不过,您应该在请求上设置 Content-Type,fetch除非您另有说明,否则将默认声明字符串是纯文本。

这是从 JS fetch() 检索发布数据时 PHP 的预期行为吗?

不。当 PHP 不支持请求正文的内容类型时,这是预期的行为。

无论如何我可以自动将内容放在 $_POST 中吗?

发送表单编码或多部分数据而不是 JSON 编码数据。