如何使用带有reactjs的php rest api?

I want to create a frontend using react for my PHP rest API. I try to read the data from the rest api but I can't manage to fetch it properly. I tested all the requests in Postman and they work fine, but I have no clue why they don't work in react.

I tried to do it with axios/fetch/get but I always get the same error TypeError: items.map is not a function. Should I rewrite my rest API? My API is returning a JSON and I don't know if I need to decode it in react?

My php code:

public function read() {
    // Create query
    $query = 'SELECT * FROM ' . $this->table ;

    // Prepare statement
    $stmt = $this->conn->prepare($query);

    // Execute query
    $stmt->execute();

    return $stmt;
}

API readUM.php

<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include_once '../../config/Database.php';
include_once '../../models/Post2.php';
// Instantiate DB & connect
$database = new Database();
$db = $database->connect();
// Instantiate  post object
$post = new Post2($db);
// Blog post query
$result = $post->read();
// Get row count
$num = $result->rowCount();
// Check if any posts
if ($num > 0) {
// Post array
$posts_arr = array();
 $posts_arr['data'] = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    extract($row);
    $post_item = array(
        'id' => $id,
        'name' => $name,
        'location' => $location,
        'type' => $type,
        'logo' => $logo
    );
    // Push to "data"
    //array_push($posts_arr, $post_item);
    array_push($posts_arr['data'], $post_item);
}
// Turn to JSON & output
echo json_encode($posts_arr);
} else {
// No Posts
echo json_encode(
    array('message' => 'No Posts Found')
);
}

Result in postman:

{
"data": [
    {
        "id": "1",
        "name": "Test",
        "location": "Cluj",
        "type": "Test",
        "logo": null
    }
]
}

My react code:

 constructor(props) {
    super(props);
    this.state = {
        items: [],
        isLoaded: false,
    }
}

componentDidMount() {

    fetch('http://localhost/fak/api/post/readUM.php')
        .then(res => res.json())
        .then(json => {
            this.setState({
                isLoaded: true,
                items: json,
            })
        });
}

render() {

    let {isLoaded, items} = this.state;

    if (!isLoaded) {
        return <div>Loading...</div>
    } else {
        return (
            <div className="App ">
                <ul>
                    {items.map(item => (
                        <li key={item.id}>
                            Name:  {item.name} | Location:{item.location} 
                        </li>
                    ))};
                </ul>
            </div>
        );
    }
    }
}

Console.log(json):

Object
data: Array(1)
0: {id: "1", name: "Test", location: "Cluj", type: "Test", logo: null}
length: 1
__proto__: Array(0)
__proto__: Object
dongluxin6711
dongluxin6711 谢谢你,先生!这对我有用!!!!
一年多之前 回复
dongzhuanlei0768
dongzhuanlei0768 尝试更改项目:json,到项目:json.data,
一年多之前 回复
dt20081409
中国通信 CORS?检查网络响应
一年多之前 回复
dsgtew3241
dsgtew3241 把console.log(json)放在你的fetch方法中,这样你就可以知道你是否得到了响应
一年多之前 回复
doy57007
doy57007 你可以在this.setState之前添加console.log(json)({show以便我可以看到从API返回的数据是什么?
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐