node.js - YouTube PlaylistItems API 在使用 JSON.parse() 时导致语法错误
问题描述
我在我的 NodeJS 代码中有 2 次对 YouTube v3 API 的调用:频道和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 周前,这段代码可以正常工作而不会引发任何错误,我不知道发生了什么变化,似乎也无法弄清楚。这可能是什么原因造成的?
解决方案
10分钟后,我找到了解决办法!该变量rawData
包含 aBuffer
并且对其进行了更多研究,我认为我应该在调用它之前使用Buffer.concat()
on 。事实证明,这正是所需要的。rawData
JSON.parse()
在编写此代码仅 6 个月后,我仍然不确定这是如何导致问题的,但这往往会发生。
更改代码:
res.on('end', () => {
try {
resolve(JSON.parse(Buffer.concat(rawData)));
} catch (error) { console.error(`An error occurred parsing the YouTube API response to JSON, ${error}`); }
});
推荐阅读
- r - R可以用ggplot反转调色板吗?
- android - 无法返回上一页
- c# - GroupBy 和按条件计数实体框架
- javascript - Bootstrap-vue 将 svg 图像显示为导航项?
- flutter - 如何用鼠标拖动滚动条?
- python - Python中的Elasticsearch多字段查询请求
- flutter - 如何在数字键盘上添加新行按钮。带有电话列表的 TextFormField
- javascript - TypeError:如果'false'没有按预期工作
- node.js - Discord.js Bot - 在我的情况下如何处理 UnhandledPromiseRejectionWarning
- android - 将 firebase 数据库中的数据读入类不起作用