简体   繁体   中英

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

I have a React app running in localhost and backend REST APIs running in localhost. When I try to make a POST call to REST API, the call is successful. But the body in empty.

The sample code can be found below.

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));

Call is successful. res looks like: returned object

Same code works fine in Postman. Also all the GET API calls work fine from the same react app.

Two problems

  1. You don't return anything in the first then() and
  2. You need to use res.json() promise to access the data.

try something like:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM