我试图从我创建的外部JSON访问数据。该JSON上的get请求工作,我用postman测试了它。这是我的代码:
import "./Feedback.css";
import { useState, useEffect } from "react";
export default function Feedback() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch('http://localhost:8000/', {
mode: 'no-cors'
})
.then((response) => {
if (!response.ok) {
throw new Error(
`This is an HTTP error: The status is ${response.status}`
);
}
return response.json();
})
.then((actualData) => {
setData(actualData.data);
setError(null);
})
.catch((err) => {
setError(err.message);
setData([]);
})
.finally(() => {
setLoading(false);
});
}, []);
return (
<div className="Feedback">
<h1>Feedback List</h1>
{loading && <div>A moment please...</div>}
{error && (
<div>{`There is a problem fetching the data - ${error}`}</div>
)}
<ul>
{data &&
data.map(({data }) => (
<li key={data.author.id}>
<h3>{data.author.username}</h3>
<p>{data.author.email}</p>
</li>
))}
</ul>
</div>
);
}
我的json看起来像这样:
{
"data": [
{
"author": {
"about_me": "Memory when air true.",
"avatar_url": "https://www.gravatar.com/avatar/45c4df639b815ffffb06d9d3df4466e1?d=identicon",
"email": "breed@example.net",
"first_seen": "2023-03-26T14:26:07.708305Z",
"id": 1,
"last_seen": "2023-03-26T16:20:22.923657Z",
"posts_url": "/api/users/1/posts",
"url": "/api/users/1",
"username": "kevinwashington"
},
"id": 90,
"text": "Figure the impact song think. Magazine throughout college site knowledge.",
"timestamp": "2023-03-23T18:07:23Z",
"url": "/api/posts/90"
},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items},
{5 items}
],
"pagination": {
"count": 25,
"limit": 25,
"offset": 0,
"total": 43
}
}
在我的网站上,它显示了:“反馈列表获取数据时出现问题-这是一个HTTP错误:状态为0“我做错了什么,我怎么能用他们所有的数据显示数据中的所有作者
1条答案
按热度按时间3pvhb19x1#
尝试从
response()
部分删 debugging 误消息。如果您在任何时候输入then()
块时都使用then().catch()
,则响应成功。因此,实际上您正在创建错误,而没有错误可能是因为response.ok
不存在。您还需要删除no-cors
。此外,map函数没有返回任何内容,这将导致没有数据显示。请尝试将代码更新为: