【发布时间】:2020-08-17 07:57:34
【问题描述】:
我的 NodeJS 代码中有 2 个对 YouTube v3 API 的调用:channels 和 PlaylistItems。它们都返回 JSON 并且对第一个调用的响应被解析得很好,但是解析对第二个调用的响应会导致语法错误。我不确定这是我这边的错误还是 PlaylistItems API 端点中的错误。
这是我的代码(去掉了不相关的部分):
// At start of the bot, fetches the latest video which is compared to if an announcement needs to be sent
function setLatestVideo () {
fetchData().then((videoInfo) => {
if (videoInfo.error) return;
latestVideo = videoInfo.items[0].snippet.resourceId.videoId;
});
}
// Fetches data required to check if there is a new video release
async function fetchData () {
let path = `channels?part=contentDetails&id=${config.youtube.channel}&key=${config.youtube.APIkey}`;
const channelContent = await callAPI(path);
path = `playlistItems?part=snippet&maxResults=1&playlistId=${channelContent.items[0].contentDetails.relatedPlaylists.uploads}&key=${config.youtube.APIkey}`;
const videoInfo = await callAPI(path);
return videoInfo;
}
// Template HTTPS get function that interacts with the YouTube API, wrapped in a Promise
function callAPI (path) {
return new Promise((resolve) => {
const options = {
host: 'www.googleapis.com',
path: `/youtube/v3/${path}`
};
https.get(options, (res) => {
if (res.statusCode !== 200) return;
const rawData = [];
res.on('data', (chunk) => rawData.push(chunk));
res.on('end', () => {
try {
resolve(JSON.parse(rawData));
} catch (error) { console.error(`An error occurred parsing the YouTube API response to JSON, ${error}`); }
});
}).on('error', (error) => console.error(`Error occurred while polling YouTube API, ${error}`));
});
}
我遇到的错误示例:Unexpected token , in JSON 和 Unexpected number in JSON
直到大约 2 周前,这段代码可以正常工作而不会引发任何错误,我不知道发生了什么变化,而且似乎无法弄清楚。这可能是什么原因造成的?
【问题讨论】:
标签: node.js json youtube-api