0

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.

Blerdijan
  • 15
  • 1
  • 4
  • Try it with the following change: `.then(response => response.json())`. Your problem resolves from the format you retrieves the response data. `response.text()` returns the data as a simple string. `response.json()` returns the data as a Object. – IISkullsII Jul 29 '22 at 12:19
  • Yes, this was the problem. Thank you very much! – Blerdijan Jul 29 '22 at 12:22

1 Answers1

0

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()

Blerdijan
  • 15
  • 1
  • 4