0

I am trying to fetch data from from php api here is the code of api

<?php 
if(!empty($_POST)){
        $array = ["name" => "vasu" ,"json" => "created at 2021"];
     print_r(json_encode($array));    
    }else{
        $array = ["error" => 22];
        print_r(json_encode($array));
    }
?>

Here is the code of my react nativ fetch method

 fetch(url,{
     method : "POST",
     body : JSON.stringify({
       name : "vasu"
     })
   })
    .then((response) => response.json())
    .then((json) => {
      console.log(json);
    })
    .catch((error) => {
      console.error(error);
    });

Output

{"error":22}

It means I can't get anything in $_POST How to fix this problem

  • You're posting the data in the **body** of your request. You will need to use `file_get_contents('php://input');` to access it on the server side. You will have to use `FormData` to post data the way you you're trying to access it. – codemonkey Feb 12 '21 at 23:53
  • To add into @codemonkey comment, checkout it out here: https://stackoverflow.com/questions/46640024/how-do-i-post-form-data-with-fetch-api – Han Feb 13 '21 at 00:01

1 Answers1

0

Hi there the Issue was that you are using JSON.stringyfy while declaring your body which is not correct that's why it is not taking the value of body and giving you error

you should be use that as

 fetch(url,{
 method : "POST",
 body : {
   name : "vasu"
 }
})
 .then((response) => response.json())
 .then((json) => {
  console.log(json);
 })
 .catch((error) => {
  console.error(error);
});
Talha Akbar
  • 462
  • 3
  • 15