为何我的代码解析失败?报错TypeError: 无法读取undefined的response属性
解析CalDAV数据时的TypeError错误解决
问题根源
你代码中尝试通过result['D:multistatus']['D:response']获取数据,但从提供的result结构来看:
- 顶层对象的键是
multistatus(无D:前缀) multistatus内部的响应列表键是response(同样无D:前缀)
这就导致result['D:multistatus']返回undefined,继续访问其response属性时触发了TypeError: Cannot read properties of undefined (reading 'response')。
修正代码
将键名调整为与实际数据结构匹配的形式:
var data = result.multistatus.response; if(data) { data.map((event) => { // 注意:需确认event内部的D:propstat等带前缀的键是否与实际返回结构一致 var ics = event['D:propstat'][0]['D:prop'][0]['C:calendar-data'][0]; var jcalData = ICAL.parse(ics); var vcalendar = new ical.Component(jcalData); var vevent = vcalendar.getFirstSubcomponent('vevent'); reslist.push(vevent) }); }
额外优化建议
- 使用可选链操作符(
?.)做安全访问,避免后续因数据结构变动再次出现类似错误:var data = result?.multistatus?.response; - 提前打印
event的结构,确认D:propstat、D:prop等带命名空间前缀的键是否存在,避免后续解析calendar-data时出错。
内容的提问来源于stack exchange,提问作者Universe
相关产品推荐
相关产品推荐

