gpt4 book ai didi

javascript - 如何使用 Fetch API 显示来自 API 的图像?

转载 作者:行者123 更新时间:2023-12-03 01:15:04 25 4
gpt4 key购买 nike

首先,我正在使用 Unofficial Xbox API我正在尝试显示端点示例 CLICK HERE 中的图像网站中提供了该信息。

所以我使用了一个带有 Fetch API 函数回调的按钮:

document.getElementById('getScreenshots').addEventListener('click', getScreenshots);

function getScreenshots(){
// Get data from URL
fetch('https://xboxapi.com/v2/screenshots/1144039928',{
headers: new Headers({
"X-Auth": "HERE-GOES-MY-API-KEY",
"Content-Type": "application/json",
})
})
.then((res) => res.json())
.then((data) => {
let output = '<h5>List of Recent Screenshots</h5>';
data.forEach(function(screenshot){
output += `
<ul>
<li>ID: ${screenshot.screenshotId}</li>
<li>Published at: ${screenshot.datePublished}</li>
<li><img src="${screenshot.uri}"></li>
</ul>
`;
});
document.getElementById('screenshots').innerHTML = output;
})
.catch((err) => console.log(err))
}
        <button id="getScreenshots">Get Screenshots</button>
<ul id="screenshots"></ul>

但每次我尝试请求它时,图像都不会显示,并且控制台会为每个图像抛出 404 错误。这就是我要说的: enter image description here

有人可以帮我解决这个问题吗?

提前致谢。

更新,这是我使用Postman时得到的json数据:

"thumbnails": [
{
"uri": "https://screenshotscontent-t5002.xboxlive.com/xuid-2535443387655711-public/29cd392a-6758-4926-8396-44aa77822ac6_Thumbnail.PNG",
"fileSize": 0,
"thumbnailType": "Small"
},
{
"uri": "https://screenshotscontent-t5002.xboxlive.com/xuid-2535443387655711-public/29cd392a-6758-4926-8396-44aa77822ac6_Thumbnail.PNG",
"fileSize": 0,
"thumbnailType": "Large"
}
],
"screenshotUris": [
{
"uri": "https://screenshotscontent-d5002.xboxlive.com/xuid-2535443387655711-private/29cd392a-6758-4926-8396-44aa77822ac6.PNG?sv=2015-12-11&sr=b&si=DefaultAccess&sig=5Is2Shl9m0c85yI0Vq%2BTRs3cuwYDvUR2BBWrD2%2FpkIw%3D",
"fileSize": 1255362,
"uriType": "Download",
"expiration": "2018-08-29 04:51:56"
}
],
"xuid": 2535443387655711,
"screenshotName": "",
"titleName": "Halo: The Master Chief Collection",
"screenshotLocale": "en-US",
"screenshotContentAttributes": "None",
"deviceType": "Durango",
"screenshotDetails": "https://xboxapi.com/v2/2535443387655711/screenshot-details/d1adc8aa-0a31-4407-90f2-7e9b54b0347c/29cd392a-6758-4926-8396-44aa77822ac6"

},

最佳答案

screenshot.screenshotUris.uri 将是未定义的,因为 screenshot.screenshotUris 是一个数组。所以你需要:

screenshot.screenshotUris[0].uri

或者制作一个像

这样的循环

screenshot.screenshotUris.forEach(function(el) { ...el.uri... })

关于javascript - 如何使用 Fetch API 显示来自 API 的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52052133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com