调用YouTube API获取视频详情时遇TypeError错误求助
问题原因与修复方案
错误根源
报错TypeError: Cannot read properties of undefined (reading 'snippet')的核心原因:
- 在
fetchVideoDetails函数中,调用YouTube Videos API时,请求的part参数仅指定了statistics,API返回的数据里不包含snippet字段,代码却试图访问data.items[0].snippet.title,导致读取undefined的属性报错。 - 未处理API返回无数据(
data.items为空)的情况,存在数组越界风险。
修复后的完整代码
// 替换为你的YouTube API密钥 const API_KEY = 'YOUR_YOUTUBE_API_KEY'; function fetchYouTubeData(searchQuery) { const url = `https://www.googleapis.com/youtube/v3/search?part=snippet&q=${encodeURIComponent(searchQuery)}&key=${API_KEY}`; const response = UrlFetchApp.fetch(url); const data = JSON.parse(response.getContentText()); const videos = data.items?.filter(item => item.id.kind === 'youtube#video') || []; const results = []; videos.forEach(video => { const videoId = video.id.videoId; const videoDetails = fetchVideoDetails(videoId); if (videoDetails) { results.push(videoDetails); } }); return results; } function fetchVideoDetails(videoId) { // 同时请求snippet和statistics字段,获取标题、统计数据 const url = `https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id=${videoId}&key=${API_KEY}`; try { const response = UrlFetchApp.fetch(url); const data = JSON.parse(response.getContentText()); // 检查是否返回有效视频数据 if (!data.items || data.items.length === 0) { console.log(`未找到视频ID: ${videoId}的详情`); return null; } const videoItem = data.items[0]; return { videoId: videoId, title: videoItem.snippet?.title || '无标题', description: videoItem.snippet?.description || '无描述', views: videoItem.statistics?.viewCount || '0', likes: videoItem.statistics?.likeCount || '0', // YouTube API已不再返回dislikeCount,此处保留兼容逻辑 dislikes: videoItem.statistics?.dislikeCount || '不可用' }; } catch (error) { console.log(`获取视频详情失败: ${error.message}`); return null; } }
关键修改点
- 调整
fetchVideoDetails的API请求URL,将part参数改为snippet,statistics,确保返回标题、描述等snippet信息。 - 增加
try-catch捕获API请求异常,避免单个视频请求失败导致整个函数崩溃。 - 添加空值检查:判断
data.items是否存在,使用可选链操作符(?.)避免访问undefined属性。 - 处理YouTube API不再提供dislikeCount的情况,给出默认提示文本。
内容的提问来源于stack exchange,提问作者NinjaR
相关产品推荐
相关产品推荐

