获取快速API数据



[数据截图][1]你好,我试图从引用API(引用,作者)获取信息,但我很难获取作者数据。你能帮帮忙吗?

(特别是

下面的代码行)
.then(response=> {document.getElementById("quoteauthor").innerHTML=response.originator[1]})

)下面是JS文件

const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'Key',
'X-RapidAPI-Host': 'quotes15.p.rapidapi.com'
}
};
function getQuote(){
fetch('https://quotes15.p.rapidapi.com/quotes/random/', options)
.then(response => response.json())
.then(response=> {document.getElementById("quote").innerHTML=response.content})
.then(response=> {document.getElementById("quoteauthor").innerHTML=response.originator[1]})
.catch(err => console.error(err));}

下面是HTML文件主体部分

<body>
<button onclick="getQuote()">Give me a quote!</button>


<div>

<p style="text-align: center" id="quote"></p>;
<p style="text-align: center" id="quoteauthor"></p>
</div>
<script src="script.js"></script>
</body>
[Not displaying author][2]

[1]: https://i.stack.imgur.com/XD17C.jpg
[2]: https://i.stack.imgur.com/mejNQ.jpg

你没有得到"quoteauthor">因为一个错误:">TypeError: response is undefined"。

你可以试着调试你的代码,以便找出在哪里获取是失败的(可能是因为捕获部分),也使用console.log()这将有助于你的调查。

如果你不介意的话,让我稍微重写一下你的代码片段。

HTML部分

<body>
<button id="getQuote">Give me a quote!</button>
<div>
<p style="text-align: center" id="quote"></p>
<p style="text-align: center" id="quoteAuthor"></p>
</div>
<script src="script.js"></script>
</body>

JavaScript部分

const quoteButton = document.getElementById('getQuote');
const quote = document.getElementById('quote');
const quoteAuthor = document.getElementById('quoteAuthor');
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key' : 'your_key',
'X-RapidAPI-Host': 'quotes15.p.rapidapi.com'
}
};
quoteButton.addEventListener('click', getQuote);
async function getQuote() {
try {
const response = await fetch('https://quotes15.p.rapidapi.com/quotes/random/', options);
if (!response.ok) {
throw new Error(`Getting error: ${response}`);
}
const data = await response.json();
quote.innerHTML = data.content;
quoteAuthor.innerHTML = data.originator.name;
} catch (error) {
console.log(error);
}
}

使用这种方法,您将获得引用和作者

我认为问题出在你尝试了

response.originator[1]

反应。Originator不是一个数组,而是一个映射,所以你应该为作者的名字做

response.originator.name

和引号本身

response.content

最新更新