unable to access data in fetch API call

I am trying to fetch data from https://lighthouse-dot-webdotdevsite.appspot.com//lh/newaudit I am getting result in promise but I need a specific thing like performance(score) and SEO all the important things and firstly I did that with help of the following code

<script>
   
  fetch("https://lighthouse-dot-webdotdevsite.appspot.com//lh/newaudit", {
    method: "POST",
    body: JSON.stringify({
    "url": "https://piyushsthr.netlify.app",
    "replace": true,
    "save": false
  }),
    headers: {
      "Content-Type": "application/json; charset=utf-8"
    },
    credentials: "same-origin"
  }).then(function(response) {
    response.status
    response.statusText
    response.headers
    response.url
  
    return console.log(response.text())
  }).catch(function(error) {
    error.message
  })

    </script>

now it is returning promise but after doing console.log(text.value.lhrSlim.performance.score()) it is not showing logs can you guys help for this.

Answer

fetch API returns a json() Promise response which you can chain a .then() method to get the actual values you need.

So it should like this

fetch("https://lighthouse-dot-webdotdevsite.appspot.com//lh/newaudit", {
    method: "POST",
    body: JSON.stringify({
    "url": "https://piyushsthr.netlify.app",
    "replace": true,
    "save": false
  }),
    headers: {
      "Content-Type": "application/json; charset=utf-8"
    },
    credentials: "same-origin"
  })
   .then(res => res.json()) // this is the line you need
   .then(function(data) {


    console.log(data)
    return data;

  }).catch(function(error) {
    error.message
  })

Leave a Reply

Your email address will not be published. Required fields are marked *