简体   繁体   中英

Why can't I receive the body from a POST request even though it is returned in Postman?

I am using the fetch() API in JavaScript to retrieve information from my flask backend server. I test the same URL and endpoint in postman, and I receive the response body. However, when I perform the same POST through fetch() and process the Response using async/await , I get body: undefined on the client side. Below is the code:

const result = await fetch(`${BACKEND_URL}/auth`, {
        method: "POST",
        body: newUserBasicString, // some payload
        headers: {
          "Content-type": "application/json",
        },
      });
      console.log(JSON.stringify(result));

BACKEND_URL is a forwarded ngrok https url. Why am I receiving no body?

You still need to handle the data returned by the fetch api, as be default it does not know how to handle the body. If you want to do it inline this should return what you want.

const result = await fetch(`${BACKEND_URL}/auth`, {
        method: "POST",
        body: newUserBasicString, // some payload
        headers: {
          "Content-type": "application/json",
        },
      }).then(response => response.json()) 
      // .json() for application/json response
      // .text() for application/text response
      console.log(JSON.stringify(result));

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