Promise 错误TypeError: Cannot read properties of undefined (reading ‘videoId’)
问题描述
我在使用YouTube API以网格形式显示视频时遇到了标题中的错误。我的代码如下:
fetch('https://youtube.googleapis.com/youtube/v3/search?part=snippet&maxResults=12&q=software%20quality%20assurance&type=video&videoDuration=short&key=AIzaSyA0c9e2X5lcxnbWGg2QaUJvdo4aDQlXiNM')
.then((result)=>{
return result.json();
})
.then(data=>{
console.log(data);
let videos = data.items;
let videoId = videos.id.videoId;
let videoContainer = document.querySelector(".youtube_container");
videos.forEach((video)=>{
videoContainer.innerHTML +=
//document.write(video.snippet.title);
`<iframe src = "https://www.youtube.com/embed/${videoId}" frameborder = "0" allowfullscreen></iframe>`;
})
})
问题可能是什么?
解决方案
根据你返回的json,视频是一个数组。
fetch(url)
.then((result)=>{
return result.json();
})
.then(data=>{
// data.items is an array so you need to loop through items.
for (let i = 0; i < data.items.length; i++) {
const video = data.items[i]
const videoId = video.id.videoId;
// do what you want here.
}
})