我想为我的PHP rest API使用react创建一个前端。我尝试从其余api中读取数据,但无法设法正确获取它。我在Postman中测试了所有请求,它们都可以正常工作,但是我不知道为什么它们在响应中不起作用。
我试图用axios / fetch / get来做到这一点,但是我总是遇到相同的错误TypeError:items.map不是一个函数。我应该重写我的其余API吗?我的API返回的是JSON,我不知道是否需要在响应中对其进行解码?
我的php代码:
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')
);
}
邮递员结果
{
"data": [
{
"id": "1",
"name": "Test",
"location": "Cluj",
"type": "Test",
"logo": null
}
]
}
我的反应代码:
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