Sending data to PHP server with Fetch API (POST method and JSON preferred)

一笑奈何 提交于 2020-04-30 10:30:56

问题


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

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:

  • I CAN'T send JSON post to PHP server

  • I CAN send form-data post to LOCAL PHP

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

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);
});

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.

UPDATE

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.

  • I CAN'T send JSON post to PHP

  • I CAN send form-data post to PHP

UPDATE

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.

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

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);

回答1:


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);
}

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));

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"
      }
  };

finally use fetch like this:

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

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



来源:https://stackoverflow.com/questions/58464121/sending-data-to-php-server-with-fetch-api-post-method-and-json-preferred

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!