React 应用程序中的 fetch 调用没有 return body,相同的调用在 postman 中工作正常

fetch call in react app doest not return body, same call works fine with postman

我在本地主机中有一个 React 应用程序 运行,在本地主机中有一个后端 REST APIs 运行。 当我尝试对 REST API 进行 POST 调用时,调用成功。但是 body 是空的。

示例代码如下。

const body = await fetch("url", {
            method : 'POST',
            headers: {
                "Accept" : "application/json",
                "Content-Type" : "application/json"
            },
            body: JSON.stringify(comp)
        }).then((res) => { 
            console.log(res);
        }).then(data => console.log(data));

调用成功。 水库看起来像: returned object

相同的代码在 Postman 中运行良好。此外,所有 GET API 调用都可以在同一个 React 应用程序中正常工作。

两个问题

  1. 在第一个 then()
  2. 中你没有 return 任何东西
  3. 您需要使用 res.json() 承诺才能访问数据。

试试这样的东西:

const req = await fetch("url", {
            method : 'POST',
            headers: {
                "Accept" : "application/json",
                "Content-Type" : "application/json"
            },
            body: JSON.stringify(comp)
        });

const data = await req.json();

console.log(data)