我如何在 fetch 调用中解析简单的 json 响应

amm*_*mmy 2 json fetch reactjs

我在获取响应中获取简单的 json 对象。当我尝试访问该对象时,它被捕获。

this my reposnse
{
    "islogin": true
}



 fetch(url, data)
      .then(res => {console.log(res);return res.json()})
      .then(
        (result) => {
          console.log("rsult",JSON.stringify(result));
          console.log(result.islogin);
          console.log("1");
          console.log("authentication success");
        })
      .catch((error) => { window.alert("error", error);
        console.log("authentication failed");
      });
Run Code Online (Sandbox Code Playgroud)

我期望 result.islogin 为 true/false。但它不会进入 then(result) 回调。

Aja*_*ese 5

fetch(URL, {
    method: "POST", // "GET/POST"
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
})
.then(r => r.json())
.then(r => {
   console.log('Response', r) // You will get JSON response here.
}).catch(error => console.error('Error', error))
Run Code Online (Sandbox Code Playgroud)

由于缺少内容类型标头,有时由于未对请求负载进行字符串化,我遇到了类似的问题。尝试这段代码,看看它是否有效。上面是我在我的项目中使用的工作片段。