dsfasdfsda234234 2017-11-10 06:09
浏览 298
已采纳

React本机http获取请求无效

I'm new to react native trying to do the http request using fetch method (also tried axios). I'm using PHP as backend. What I'm trying is to print the JSON object returned from server in react native.

I'm sure that the response is returning from server cause I printed the result and it is a JSON array. But when I consoled the responseData using Chrome dev tools I got this []. I don't know where the mistake is.

index.js

    componentDidMount(){

        fetch('http://xxxxxxxxxx/result.php', {
            method: 'GET',
        }).then(response =>response.json())
          .then((responseData) =>
          {
              console.log(responseData);
              this.setState({
                  user: (responseData.name),
                  loaded:true,
              })

        });         
}
    render(){
        return(
        <Card>  
  <CardTitle style={styles.containerStyle} title={this.state.user} />
</Card>
        );
    }
}

Also my php is script is as follows

result.php

<?php
include 'db.php';
$check_json = file_get_contents('php://input');

$obj1= json_decode($check_json);
$uid =$obj1->{'uuid'};
$blood = $obj1->{'bloodgroup'};
$loc = $obj1->{'place'};
$prep =$mysqli->prepare("select token,name,uuid from signup where location 
like '".$loc."%' and bloodgroup= ?");
$prep->bind_param("s",$blood);
$prep->execute();
$result= $prep->get_result();
$payload= array();
while($row= $result->fetch_array(MYSQL_ASSOC)){
   $payload[]= array('name' =>$row['name']
                    'uuid' =>$row['name']);
}
$obj2 =json_encode($payload);
echo $obj2;
?>

and the response from server is

 [{"name":"angel","uuid":"b4b8a266-60cf-4e30-a778-596316d1a4a2"}]
  • 写回答

3条回答 默认 最新

  • douzhi4991 2017-11-10 06:29
    关注

    Try using axios. You can check the docs here After you have done npm install axios and imported axios into your component you can try:

    componentDidMount(){
    axios
      .get('https://www.your-url.com/path-to-your-php-api')
      .then(({ data })=> {
        this.setState({ 
          user: data.name
        });
      })
      .catch((err)=> {})
    }
    

    if you still have problems, post the url that returns JSON so I can take a look.

    Check your PHP API, if the object is returning empty, make sure to encode json. Here is an example you can try

    $myObj->name = "Michel Arteta";
    $myObj->age = 30;
    $myObj->city = "New York";
    
    $myJSON = json_encode($myObj);
    
    echo $myJSON;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功