问题
My PHP script isn't receiving anything via POST from fetch. What am I doing wrong?
Javascript:
fetch("http://127.0.0.1/script.php", {
method: "post",
body: "inputs=" + JSON.stringify({param: 7})
}).then(response => response.json()).then(response => {
console.log(response);
});
script.php:
echo "\nprinting POST:\n";
print_r($_POST);
echo "\nprinting GET:\n";
print_r($_GET);
die();
Console:
printing POST: Array ( )
printing GET: Array ( )
回答1:
You're not adding any url parameters (hence $_GET
is empty) and you're not setting a Content-Type
header that will make PHP automatically parse the request body. (hence $_POST
is empty).
回答2:
There was something wrong with the htaccess file for that particular test PHP file. I've used it for posting something to the main project folder/PHP files and it went ok.
来源:https://stackoverflow.com/questions/43395576/fetch-sending-post-data