在react原生获取方法不工作



我试图从php api获取数据,这里是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));
}
?>

下面是我的react native取回方法

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

输出

{"error" 22}

这意味着我不能在$_POST中得到任何东西如何解决这个问题

你好,问题是你使用的是JSON.stringyfy当声明你的body时这是不正确的这就是为什么它没有取body的值并给你错误

你应该用

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

最新更新