首页 > 解决方案 > 在 react nativ fetch 方法中不起作用

问题描述

我正在尝试从 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 nativ fetch 方法的代码

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

输出

{“错误”:22}

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

标签: phpreactjsreact-native

解决方案


您好问题是您在声明您的身体不正确的同时使用JSON.stringyfy这就是为什么它没有获取身体的价值并给您错误

你应该用它作为

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

推荐阅读