首页 > 解决方案 > 无法访问 fetch API 调用中的数据

问题描述

我正在尝试从https://lighthouse-dot-webdotdevsite.appspot.com//lh/newaudit获取数据 我得到了承诺但我需要一个特定的东西,比如性能(分数)和 SEO 所有重要的事情,首先我在以下代码的帮助下做到了

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

现在它正在返回承诺,但是在执行 console.log(text.value.lhrSlim.performance.score()) 之后它没有显示日志你们可以帮忙吗?

标签: javascriptapi

解决方案


fetch API 返回一个json() Promise响应,您可以链接一个.then()方法来获取您需要的实际值。

所以它应该像这样

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

推荐阅读