首页 > 解决方案 > 如何使用 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()

标签: javascriptfetch

解决方案


响应对象有一个.json()函数,您可以返回另一个函数,Promise结果是来自响应主体的反序列化 JSON 作为 JavaScript 对象。


推荐阅读