试图从JS中获取API,我返回的JSON返回undefined?是的,它是有效的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);
然后fetch下的函数实际上没有返回值。所以console.log(getJsonResponse...
记录未定义。 getJsonResponse
必须返回一些东西(无论是承诺还是价值)。
而不是response.json().then(data => { return data; })
,只是return response.json();
尝试在response.json()之前追加return。休息似乎很好。被调用的函数应该返回一些值。
`function getJsonResponse(url) {
return fetch(url).then((response) => {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' + response.status);
return 'Looks like there was a problem.';
}
return response.json().then((data) => {
return data;
});
}).catch(function (err) {
console.log('Fetch Error :-S', err);
});
}`