javascript - 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);
解决方案
fetch 下的函数then实际上没有返回值。所以console.log(getJsonResponse...
日志未定义。getJsonResponse
必须返回一些东西(一个承诺或一个值)。
而不是response.json().then(data => { return data; })
,简单地return response.json();
推荐阅读
- c# - MVC Web App - 当条码扫描仪连接为物理键盘时,如何允许用户使用虚拟键盘?
- javascript - 使用 withRouter 后,您不应在路由器外使用 Route
- google-apps-script - 在谷歌表格中获取动态范围
- puppeteer - 使用 puppeteer-recorder 录制浏览器的视频
- jenkins - 将 job-dsl 插件从 1.50 升级到 1.72 后没有方法错误的签名
- swift - 在 Swift 中将 Double 值类型转换为 Int64,位数为 13,但它运行的系统是 32 位系统,它会失败吗?
- node.js - 请求会话不是持久的 - 快速会话
- c# - 我在编辑控制器中输入错误的类型,我该怎么办?
- python - 在python中安排一个每小时重复一次的任务和另一个每天重复一次的任务
- json - 如何使用 volley 在数据来自 json 的 recyclerview 中打开特定/不同的 Activity