Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.:

fetch("/echo/json/", {     headers: {       'Accept': 'application/json',       'Content-Type': 'application/json'     },     method: "POST",     body: JSON.stringify({a: 1, b: 2}) }) .then(function(res){ console.log(res) }) .catch(function(res){ console.log(res) }) 

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.

like image 864
Razor Avatar asked Apr 21 '15 14:04

Razor


People also ask

Can I use Fetch to post data?

Uploading JSON dataUse fetch() to POST JSON-encoded data.

How do I fetch a post request?

POST request using fetch with async/await This sends the same POST request using fetch, but this version uses an async function and the await javascript expression to wait for the promises to return (instead of using the promise then() method as above).

How get fetch data from JSON?

GET JSON dataloadNames(); await fetch('/api/names') starts a GET request, and evaluates to the response object when the request is complete. Then, from the server response, you can parse the JSON into a plain JavaScript object using await response.

What is response JSON () in fetch?

json() The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .


1 Answers

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

(async () => {    const rawResponse = await fetch('https://httpbin.org/post', {      method: 'POST',      headers: {        'Accept': 'application/json',        'Content-Type': 'application/json'      },      body: JSON.stringify({a: 1, b: 'Textual content'})    });    const content = await rawResponse.json();      console.log(content);  })();

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:

var payload = {     a: 1,     b: 2 };  var data = new FormData(); data.append( "json", JSON.stringify( payload ) );  fetch("/echo/json/", {     method: "POST",     body: data }) .then(function(res){ return res.json(); }) .then(function(data){ alert( JSON.stringify( data ) ) }) 

For endpoints accepting JSON payloads, the original code is correct

like image 103
Razor Avatar answered Oct 12 '22 21:10

Razor