保存私人数据;来自 Await Fetch 的意外响应

Saving Private Data; Undesired Response from Await Fetch

所以我试图从控制台记录 42 的以下代码中取出一个名为 data 的变量,该变量存储来自 .then() 方法的值 42:

fetch("http://localhost:8088/get/value")
.then(response => response.json())
.then(data => console.log(data));

有人告诉我我做不到,我应该尝试 await/async 所以我将我的代码重新调整为:

asyncCall();

async function asyncCall()
{
    var a = await fetch("http://localhost:8088/get/value");
    console.log(a);
}

它最终在控制台记录了整个响应,但奇怪的是,当我认为值 42 是通过正文发送时,无论是否使用正文,它都注册为 false。为什么在我正常记录之前值 42 似乎消失了? - 我该怎么做才能让控制台用 async/await 记录原始值 42?感谢以后的帮助。

您错过了在第一个版本中对 response.json() 的调用。这告诉 fetch 模块将响应主体解释为 json,否则,它可能是缓冲区或其他东西。

asyncCall();

async function asyncCall()
{
    let data = await fetch("http://localhost:8088/get/value").then(res => res.json());
    console.log(data);
}