I am trying to retrieve the PageSpeed score for the website that I am analyzing. I managed to fetch from the API successfully, but I am not able to get the Score from the API.
I found out that the score is in lighthouseResult.categories.performance.score . I tried to fetch that and I get this error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'categories').
Here is my code how I fetch the API:
fetch('https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://aviokarte.me&key=mykey')
.then(response => response.text())
.then(data => console.log(data.lighthouseResult.categories.performance.score));
I don't know what I do wrong?
When I try to do console.log(data)
it works and gives me the whole JSON back.
response.text()
returns the data as a simple string. response.json()
returns the data as an Object.
You can read more on this topic here: https://teamtreehouse.com/community/confused-about-json-vs-text
So in my case, I had to use response.json()