尝试使用React调用Wikipedia api,但找回无用的对象

我正在尝试从输入中搜索Wikipedia,它正在工作,但突然之间不再起作用。这是我对Wikipedia的呼叫,但是当我进行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

任何想法可能出了什么问题?也许我只是打了太多电话?谢谢。

adi2589900 回答:尝试使用React调用Wikipedia 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>

本文链接:https://www.f2er.com/2710977.html

大家都在问