如何使用Fetch API从API显示图像?

时间:2018-08-28 07:16:24

标签: javascript jquery html fetch-api

首先,我正在使用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

有人可以帮我吗?。

谢谢。

更新,这是我在使用邮递员时获得的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"

},

1 个答案:

答案 0 :(得分:1)

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

screenshot.screenshotUris[0].uri

或像

那样循环

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