如何从PageSpeed API获取页面速度分数?调用成功但读取performance.score报错的问题
解决PageSpeed API分数提取的TypeError问题
嘿,这问题我太熟了!你遇到的Cannot read properties of undefined (reading 'categories')错误,根源在于你处理API返回数据的方式不对。
你用了response.text()来获取数据,这个方法返回的是纯文本字符串,而不是可以直接通过点语法访问属性的JavaScript对象。虽然你用console.log(data)能看到类似JSON的内容,但它本质上还是字符串,根本没有lighthouseResult这个属性,所以自然会报错。
修正方案
把response.text()换成response.json(),这个方法会自动将API返回的JSON格式字符串解析成JavaScript对象,这样你就能顺利访问嵌套的分数属性了。修改后的代码如下:
fetch('https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://aviokarte.me&key=mykey') .then(response => response.json()) .then(data => console.log(data.lighthouseResult.categories.performance.score));
备选方案(如果你非要用text()的话)
如果因为某些原因必须用response.text(),那你需要手动将字符串解析成JSON对象,代码如下:
fetch('https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://aviokarte.me&key=mykey') .then(response => response.text()) .then(data => { const parsedData = JSON.parse(data); console.log(parsedData.lighthouseResult.categories.performance.score); });
不过第一种方案更简洁高效,推荐使用哦。
内容的提问来源于stack exchange,提问作者Blerdijan
相关产品推荐
相关产品推荐

