Node.js调用Google Calendar API报Bad Request错误的解决求助
问题解决方法
核心排查方向
时间格式不兼容
Google Calendar API要求时间参数必须符合RFC3339标准(示例:2024-05-20T14:30:00Z)。从MySQL取出的datetime/timestamp类型数据,默认字符串格式可能缺少T分隔符或Z时区标识,直接传入会触发请求错误。
解决:将数据库返回的时间转换为ISO格式,比如在JavaScript中使用:const formattedStart = new Date(eventdatestart).toISOString(); const formattedEnd = new Date(eventdateend).toISOString();注意:如果数据库存储的是本地时间,需手动转换为UTC时间,避免时区偏移导致的解析错误。
时间值无效/为空
检查数据库查询结果中是否存在null、空字符串或格式错误的时间(比如2024/05/20这类斜杠分隔格式),这类值会被Google API判定为无效请求。
解决:在代码中添加前置校验:if (!eventdatestart || !eventdateend || isNaN(new Date(eventdatestart).getTime())) { console.error('Invalid time data:', eventdatestart, eventdateend); return; }时间顺序错误
若数据库中存在eventdateend早于或等于eventdatestart的记录,Google API会拒绝请求。
解决:添加时间顺序校验:const startDate = new Date(eventdatestart); const endDate = new Date(eventdateend); if (endDate <= startDate) { console.error('End time must be after start time:', eventdatestart, eventdateend); return; }
调试技巧
在调用Google Calendar API前,打印格式化后的时间参数,确认格式是否符合要求:
console.log('Formatted Start Time:', formattedStart); console.log('Formatted End Time:', formattedEnd);
将打印出的时间替换之前的固定常量测试,若能正常运行,即可确认是时间格式问题。
内容的提问来源于stack exchange,提问作者Simmsee
相关产品推荐
相关产品推荐

