我试图从我创建的外部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";我做错了什么,我怎么能在数据中显示所有作者的所有数据
尝试从response()
部分删除错误消息。如果您在任何时候使用then().catch()
进入then()
块,则响应成功。因此,当没有错误时,您实际上正在创建一个错误,可能是因为response.ok
不存在。你也需要删除no-cors
。
此外,您没有从map函数返回任何将导致不显示数据的内容。试着这样更新你的代码:
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/')
.then((response) => {
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((d) => {
return (
<li key={d.author.id}>
<h3>{d.author.username}</h3>
<p>{d.author.email}</p>
</li>
);
})}
</ul>
</div>
);
}