使用Fetch API将数据发送到PHP服务器(首选POST方法和JSON)

问题描述:

我第一次尝试使用Fetch API,但在将 POST 数据发送到PHP服务器时遇到问题.

I'm trying Fetch API for the first time and I have problems sending POST data to a PHP server.

我正在远离 $.ajax ,并尝试使用纯JavaScript解决方案与其他服务器(有时是本地,有时不是)进行通信.现在,我试图理解Fetch API,即使它简单直观,我还是偶然发现了一个奇怪而出乎意料的问题:

I'm moving away from $.ajax and trying pure javascript solutions to communicate with different servers (sometimes local, sometimes not). Now I'm trying to understand Fetch API and, even if it's simple and intuitive, I've stumbled on a weird and unexpected problem:

  • 我无法将JSON帖子发送到PHP服务器

  • I CAN'T send JSON post to PHP server

我可以将表单数据发布发送到本地PHP

I CAN send form-data post to LOCAL PHP

我无法将表单数据发布发送到WEB URL PHP

I CAN'T send form-data post to WEB URL PHP

我可以(显然)从以上所有数据中检索数据,但是奇怪的是没有任何数据到达.通过 $ _ SERVER ['REQUEST_METHOD'] ,我可以看到,使用LOCAL路径时,按照我的要求得到"POST",但是使用WEB URL时,它在 GET 中发生了变化.由于某种原因,我不明白.

I can (obviously) retrieve data from all the above, but strangely nothing arrives. Through $_SERVER['REQUEST_METHOD'] I can see that when using the LOCAL path I get "POST" as I asked, but when using the WEB URL it changes in GET for some reason I don't understand.

url="/";
url="www.something.com";
fetch(url, {
    method: 'POST',
    body: JSON.stringify({
        test: "toast",
    })
})
.then(function(response) {
    return response.text();
})
.then(function(data) {
    console.log(data);
});

我希望只是以一种清晰明确的方式发送和接收数据.没有jquery,没有库等.我只想发送 JSON {"test":"toast"} 并在检查 $ _ POST 变量时在PHP文件上找到它.

I expect just to send and receive data in a solid and clear way. No jquery, no libraries, etc. I just want to send a JSON {"test":"toast"} and find it on the PHP file when checking the $_POST var.

似乎本地URL和Web URL的问题在于这种差异:www.something.com/test => www.something.com/test/index.php.由于某种原因,没有index.php时,它将拒绝POST数据(但无论如何都读取回显的信息).但是关于JSON的问题仍然存在.

It seems that the problem with local and web urls were on this difference: www.something.com/test => www.something.com/test/index.php. Without index.php for some reason it refused the POST data (but read the echoed info anyway). But the problem about JSON remain.

  • 我无法将JSON帖子发送到PHP

  • I CAN'T send JSON post to PHP

我可以将表单数据发布发送到PHP

I CAN send form-data post to PHP

我发现$ _POST和$ _GET无法与Fetch API配合使用.您必须使用 php://input 来获取所有发送到服务器的数据.

I found that $_POST and $_GET don't work well with Fetch API. You have to use php://input to get all the data sent to the server.

不知道为什么.有更好的解决方案吗?为什么ajax和XMLHttpRequest没有这种问题?

Don't know why. There's a better solution? Why ajax and XMLHttpRequest don't have this kind of problems?

注意:如果希望将数据识别为json,则必须使用标头指定它,即使从未请求过此标头,所以为什么现在呢?Fetch API是否缺少某些内容?

Note: If you want the data to be recognized as json, you have to specify it with a header, even this was never requested so why now? Is Fetch API missing something?

header('Content-Type: application/json');

$test=json_decode(file_get_contents("php://input"));
//some code
echo json_encode($test);

有两种使用Fetch API的方法:一个>

There is two ways to use Fetch API: one>

let response = await fetch(url,[Options]);

if (response.ok) { // if HTTP-status is 200-299
  // get the response body (the method explained below)
  let json = await response.json();
} else {
  alert("HTTP-Error: " + response.status);
}

第二种方法是使用纯promise语法:

and the second way is to use pure promise syntax:

fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits')
  .then(response => response.json())
  .then(commits => alert(commits[0].author.login));

现在让我们讨论一下选项和数据:您的数据必须是这样的JavaScript对象:

now lets talk about options and data: your data must be a JavaScript object like this:

      let data = {
        test: "toast",
      };

然后您可以按以下方式配置标题:

then you can config your headers like this:

let headers: {
       "Content-Type": "application/json"
      }
  };

最终像这样使用获取:

let response = await fetch(url, {
        method: "POST",
        headers:headers,
        body: JSON.stringify(data)
      });

我认为您的问题是使用FormData而不是字符串化的JavaScript对象

I think your problem is using FormData instead of stringified JavaScript object