Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Posting Data with fetch()

Does the data we post to the server have to be as a string? That's why we used JSON.stringifiy?

.

1 Answer

Dane Parchment
MOD
Dane Parchment
Treehouse Moderator 11,075 Points

Does the data we post to the server have to be as a string?

No, the data (or body), has to match what we state the request is going to send. We specify this in the 'Content-Type' property in the requests header. In our case, the Content-Type has been set to JSON. We can see this in the header object that is created in the fetch call.

headers: {
     "Content-Type": "application/json"
}

So, in this case, we are actually telling the server to expect a JSON file.


That's why we used JSON.stringifiy?

Not exactly, while JSON.stringify() does convert an object into a String, it is important to realize what kind of String it is creating: A JSON String. Remember, JSON.stringify will convert an Object into the notation used by JSON. So instead of sending the object itself, we send the JSON representation of the object. That is why we use the JSON.stringify() method.


But if we get JSON back, it must be parsed to JSON format--so we use JSON.parse?

Precisely, the server responds with a JSON String, so we use JSON.parse() to convert it back into a JavaScript Object.

Really good answer @Dane Parchment