javascript - 无法访问 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()) 之后它没有显示日志你们可以帮忙吗?
解决方案
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
})
推荐阅读
- java - 如何在 Vaadin 8 中绑定外键
- r - R - Matching strings to dictionary and replacing
- c - 我可以使用动态链接将 go 嵌入到我的 C/C++ 项目吗?
- retrofit2 - RxJava subscribe onNext is not called when adding element asynchronously
- visual-studio - Getting/setting Track Changes setting property value trough DTE in Visual Studio 2019
- php - 双重提交表格
- vb.net - 字段留空时的 Visual Basic 错误
- java - 使用 Google Maps Android Marker Clustering Utility 时无法实例化 appComponentFactory
- python - 在带有 MySQL 后端的 Django 上,“非法混合排序规则 (utf8_general_ci,IMPLICIT) 和 (utf8mb4_general_ci,COERCIBLE) 用于操作 '='”
- lilypond - Lilypond:在歌词中强制换行