I created a React application from which I call a server built on PHP.
Here's how I call the PHP file:
const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: JSON.stringify({ name, username, password }), }; console.log(requestOptions); fetch('http://localhost/crud/requests/signup.php', requestOptions) .then(res => res.json()) .then(data => console.log(data));
This is what I have in the PHP file:
if (isset($_POST) && !empty($_POST)) { // do something }
When I print the $_POST
variable, I get an empty array. Even $_RESPONSE
is empty.
But when I try to print the input stream like this:
print_r(file_get_contents('php://input'));
Everything seems fine. Can anyone explain why this happens? I tried reading it in the documentation and looking up some forums and blogs, but wasn't satisfied with the answers.
PHP's built-in form support can only parse the
application/x-www-form-urlencoded
form and themultipart/form-data
form. What you are actually sending is a JSON serialized object with a MIME type ofapplication/x-www-form-urlencoded
.To actually send the
application/x-www-form-urlencoded
form, useURLSearchParams
instead ofJSON .stringify
:In this case, there is no need to explicitly set
Content-Type
: The browser does this automatically. To send amultipart/form-data
payload (which you may need to do if you want to upload larger files), use aFormData
object.If you ultimately want to send JSON, you should send it using the correct MIME type in the header,
application/json
. On the PHP side you will have to usejson_decode
手动解析有效负载>.