首页 > 解决方案 > 尝试使用 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

有什么想法可能会出错吗?或者,也许我只是打了太多电话?谢谢。

标签: reactjswikipedia-api

解决方案


您需要在结果上运行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>


推荐阅读