Skip to content
Advertisement

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?

Advertisement

Answer

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));
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement