首页 > 解决方案 > Fetch API 的 json 打印未定义?

问题描述

试图从 JS 中的 API 获取并且我返回的 JSON 返回未定义?是的,它是有效的 JSON,尽管 console.loging 数据显示我未定义?

function getVideos(playlistId) {
    console.log(
        getJsonResponse(composeArguments(API_RESOURCE, API_KEY, playlistId))
    );
}


function composeArguments(apiResource, apiKey, playlistId, maxResults = 50) {
    return (
        apiResource +
        "?key=" +
        apiKey +
        "&part=snippet&playlistId=" +
        playlistId +
        "&maxResults=" +
        maxResults);
}

function getJsonResponse(url) {
    fetch(url).then((response) => {
        if (response.status !== 200) {
            console.log('Looks like there was a problem. Status Code: ' + response.status);
            return;
        }

        response.json().then((data) => {
            return data;
        });
    }).catch(function (err) {
        console.log('Fetch Error :-S', err);
    });

}




getVideos(PLAYLIST_ID);

标签: javascriptfetch

解决方案


fetch 下的函数then实际上没有返回值。所以console.log(getJsonResponse...日志未定义。getJsonResponse必须返回一些东西(一个承诺或一个值)。

而不是response.json().then(data => { return data; }),简单地return response.json();


推荐阅读