'In react nativ fetch method is not working
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
Solution 1:[1]
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);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Talha Akbar |
