Skip to content
Advertisement

Fetch: POST JSON data

I’m trying to POST a JSON object using fetch.

From what I can understand, I need to attach a stringified object to the body of the request, e.g.:

JavaScript

When using jsfiddle’s JSON echo I’d expect to see the object I’ve sent ({a: 1, b: 2}) back, but this does not happen – chrome devtools doesn’t even show the JSON as part of the request, which means that it’s not being sent.

Advertisement

Answer

With ES2017 async/await support, this is how to POST a JSON payload:

JavaScript

Can’t use ES2017? See @vp_art’s answer using promises

The question however is asking for an issue caused by a long since fixed chrome bug.
Original answer follows.

chrome devtools doesn’t even show the JSON as part of the request

This is the real issue here, and it’s a bug with chrome devtools, fixed in Chrome 46.

That code works fine – it is POSTing the JSON correctly, it just cannot be seen.

I’d expect to see the object I’ve sent back

that’s not working because that is not the correct format for JSfiddle’s echo.

The correct code is:

JavaScript

For endpoints accepting JSON payloads, the original code is correct

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement