【问题标题】:unable to access data in fetch API call无法访问 fetch API 调用中的数据
【发布时间】:2021-03-18 07:10:27
【问题描述】:

我正在尝试从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()) 之后它没有显示日志,你们可以帮忙吗?

【问题讨论】:

  • 响应正文中没有text.value.lhrSlim.performance.score() 的属性。我的反应与您的预期不同
  • thencatch 的promise 函数返回也没有任何意义
  • lhrSlim.performance.score() 这件事是为了从响应中获取特定内容,比如性能和速度等特定的东西
  • 通过这个 console.log(data.lhrSlim[0].score) 获得了性能

标签: javascript api


【解决方案1】:

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

【讨论】:

  • 谢谢你帮助我最后一年的项目上帝保佑你永远。
猜你喜欢
  • 2019-07-13
  • 1970-01-01
  • 2021-07-04
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
  • 2019-12-09
相关资源
最近更新 更多