从控制台调用而不是从脚本调用时,该函数有效,该如何解决?

时间:2019-04-19 09:49:11

标签: javascript fetch-api

我创建了以下函数,该函数返回带有deezer API中某些数据的json:

function load_data(url){

    const DATA = [];

    fetch(url)
        .then(response => response.json())
        .then(function (response) {
            response.data.forEach((track, index) => {

                DATA[index] = {
                    'title': track.title,
                    'artist': track.artist.name,
                    'preview': track.preview,
                    'cover_medium': track.album.cover_medium,
                    'cover_small': track.album.cover_small,
                    'is_played': false
                }

            });
        })

    return DATA;

}

下一个函数将数据嵌入文档中:

function embed_tracks(data) {

    data.forEach((track, index) => {

        let song = document.createElement('div');
        song.classList.add('chart__track');
        song.innerHTML = `

            <div class="chart__thumbnail">
                <div class="chart__overlay">
                    <button class="chart__button play--button"><i class="fas fa-play"></i></button>
                    <button 
                    class="chart__button pause--button">
                        <i class="fas fa-pause"></i>
                    </button>
                </div>
                <img src="${track.cover_medium}" class="chart__cover">
            </div>
            <div class="chart__details">
                <p class="chart__artist">${track.artist}</p>
                <p class="chart__song">${track.title}</p>
                <audio
                    src="${track.preview}">
                </audio>
            </div>

        `

        document.querySelector('#chart').appendChild(song);
    });
}

但是,当从脚本中调用时,它不起作用:

const DATA = load_data('https://cors-anywhere.herokuapp.com/https://api.deezer.com/chart/0/tracks');
embed_tracks(DATA);

但是从控制台调用时,它可以正常工作。有人知道为什么吗?

0 个答案:

没有答案