-2

So I am making a request to an API endpoint. When I print JSONBody which is the variable data passed to POSTRequest(), I get the JSON I created printed to the log, however when I then try and JSON.Stringify() it, I get returned an empty object?

Was just wondering what I am doing wrong and how to fix it :)

getFileData()

const getFileData = () => {
    var data = {}

    // DO SOME STUFF HERE TO data

    POSTRequest(data);
}

POSTRequest()

const POSTRequest = async (JSONBody) => {
    console.log(JSONBody)
    console.log(JSON.stringify(JSONBody))
    try {
        const response = await fetch(API_ENDPOINT, {
            method: 'POST',
            body: JSON.stringify(JSONBody),
            headers: { 'Content-Type': 'application/json' }
        });
        response.json()
            .then(function (res) {
                Promise.resolve(res)
                    .then(function (finalData) {
                        console.log(finalData);
                        props.setData(finalData);
                    });
            });
    } catch (error) {
        console.log(error);
    }
} 
  • ```body: JSON.stringify(JSONBody), headers: { 'Content-Type': 'application/json' }```. You are sending a string in the body. But the content type is Json. You can do something like: ```body: {"data": JSON.stringify(JSONBody)}``` – ABDULLOKH MUKHAMMADJONOV Mar 08 '22 at 17:18
  • No, the issue is, when i do `JSON.stringify(JSONBody)`, i get returned an empty object instead of the string version of my object – StackOverflowKeepsBanningMe Mar 08 '22 at 17:19
  • 1
    (1) If you need to create JSON with `JSON.stringify`, then it means you don't have JSON yet, so naming your variable `JSONBody` is misleading. I will assume it is a JavaScript Object. (2) JavaScript objects can have a much greater variety of types and properties than JSON. For example, JavaScript properties can be non-enumerable, which means they would not be included in the JSON you get from calling `JSON.stringify`. – trincot Mar 08 '22 at 17:20
  • This seems like a similar question to [this one](https://stackoverflow.com/questions/38542265/why-does-json-stringify-return-empty-object-notation-for-an-object-that-see)? – sallf Mar 08 '22 at 17:20
  • 1
    Why do you mix `await` and `.then()`? Why `Promise.resolve(res).then(...)` when `res` is already the parsed JSON? o.O – Andreas Mar 08 '22 at 17:22
  • @trincot, I need to create a string from my object – StackOverflowKeepsBanningMe Mar 08 '22 at 17:22
  • @Andreas res returns another promise – StackOverflowKeepsBanningMe Mar 08 '22 at 17:22
  • No, it doesn't. And even if that would be the case, `Promise.resolve()` would make much less sense. – Andreas Mar 08 '22 at 17:24
  • @Andreas instead of criticising and telling me it doesn't, when it does, why don't you try and be nice and help solve the problem instead? :)) – StackOverflowKeepsBanningMe Mar 08 '22 at 17:25
  • _"help solve the problem instead?"_ -> [Using Promises - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) + [Using the Fetch API - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) – Andreas Mar 08 '22 at 17:29
  • @Andreas "Why" questions are confrontational. Do you actually care "why"? If he's done it wrong just say that. https://www.enixa.co/the-danger-of-why/ – James Mar 08 '22 at 17:42
  • @James Yes. I actually care. For questions/code like this I actually want to know why OP does it like that. And now? – Andreas Mar 08 '22 at 17:47
  • @Andreas What would be an acceptable answer to those why questions? "Because I made a mistake"? "Because I'm new and learning and got it wrong"? "Because I thought you could do X but I misunderstood"? Nothing that matters to the question. – James Mar 08 '22 at 18:02

1 Answers1

0

You're not waiting for the response from the fetch call correctly, try this:

const POSTRequest = async (JSONBody) => {
    console.log(JSONBody)
    console.log(JSON.stringify(JSONBody))

        await fetch(API_ENDPOINT, {
            method: 'POST',
            body: JSON.stringify(JSONBody),
            headers: { 'Content-Type': 'application/json' }
        }).then((response) => {
           console.log(response);
           props.setData(response);
       }).catch((error) => {
          console.log('POSTRequest error: ' + error)
       })
   });