javascript - 如何使用 async 和 await 正确地从 fetch api 获取 console.log 响应?
问题描述
在使用 async 和 await 时如何 console.log 来自 fetch API 的响应,以便您可以使用点表示法访问响应中的某些数据以更新 HTML 元素?
const url = "/api/contact"
uploadFile = async () => {
try {
const config = {
method: "POST",
body: formData
}
const response = await fetch(url, config)
if (response.ok) {
console.log(response) // does not give the json data needed to update html elements
return response
} else {
alert("Something went wrong. Try again.")
}
} catch (error) {
console.error(error)
}
}
uploadFile()
解决方案
响应对象有一个.json()
函数,您可以返回另一个函数,Promise
结果是来自响应主体的反序列化 JSON 作为 JavaScript 对象。
推荐阅读
- javascript - 为什么浏览器不能像游戏引擎那样每秒多次完全渲染 DOM,而不会与性能作斗争?
- android - 如果使用滚动视图,如何在页面底部留出空间
- python-3.x - 将 Pandas 数据框转换为包含 ID 和权重的元组列表
- sql - 如何从 SQL 查询中排除周末
- python - How to add an empty item in a dictionary in python?
- database - 在 rac 集群的一个节点上创建大小为 10gb 的独立数据库的步骤
- vb.net - VB .NET NullReferenceException,“对象引用未设置为对象的实例”,当它看起来是
- c# - 调用 CSharpCompilation.Emit 时无法加载 System.Security.Cryptography.Algorithms 错误
- javascript - 在反应传单中获取标记的纬度和经度
- postgresql - 无法从 golang Docker 容器连接到 Postgres 数据库