reactjs - 尝试使用 React 调用 Wikipedia api,但返回一个无用的对象
问题描述
我正在尝试从我的输入中搜索维基百科,它正在工作,但突然之间不再有效。这是我对维基百科的调用,但是当我 console.log 时的数据我得到了下面的响应。
const fetchResults = async () => {
const url = `https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=extracts|pageimages&pithumbsize=400&origin=*&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=${searchQuery}`;
await fetch(url)
.then(data => {
loggingContext.addLog(data);
Response {type: "cors", url: "https://en.wikipedia.org/w/api.php?format=json&act…plaintext&exsentences=1&exlimit=max&gsrsearch=dog", redirected: false, status: 200, ok: true, …}
type: "cors"
url: "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=extracts|pageimages&pithumbsize=400&origin=*&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=dog"
redirected: false
status: 200
ok: true
statusText: ""
headers: Headers {}
body: (...)
bodyUsed: false
__proto__: Response
有什么想法可能会出错吗?或者,也许我只是打了太多电话?谢谢。
解决方案
您需要在结果上运行json
(或text
)以获取数据。这两个函数返回 Promises,所以一定要等待它们。(或使用 .then,因为您在代码中使用 await 开始,所以我决定只使用 await)
示例(使用 loggingContext):
const res = await fetch(url);
const data = await res.json();
// data is your data.
loggingContext.addLog(data);
示例片段:
async function wiki() {
const url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=extracts|pageimages&pithumbsize=400&origin=*&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=dog';
const res = await fetch(url);
const data = await res.json();
document.getElementById('response').innerText = JSON.stringify(data, null, 4);
}
wiki();
<pre id="response">
Loading...
</pre>
推荐阅读
- python - Pandas Python中的多个时间范围选择
- python - 如何对列进行排序以便不显示 NaN?
- hook - 如何知道 CS 车钩何时触发?
- blazor - iis 上的随机 Blazor“未能在资源的“完整性”属性中找到有效的摘要”
- c++ - 如何从 std::thread 更改 GUI?
- php - 如何使用 JWK 验证 JWT - PHP
- python - Python Selenium 不点击无法定位的链接
- wordpress - Wordpress 致命错误:未捕获的错误:调用未定义的方法 WP_Error::get_wc_block_data()
- python - 尝试从opencv中的.mov视频读取帧时“找不到起始编号(以文件名)”
- substrate - 您如何设置在基材中开发自己的托盘