Skip to content
Fix Code Error

Fetch: POST json data

March 13, 2021 by Code Error
Posted By: Anonymous

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.

Solution

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

Answered By: Anonymous

Related Articles

  • Is CSS Turing complete?
  • How do I return the response from an asynchronous call?
  • GLYPHICONS - bootstrap icon font hex value
  • Reference - What does this regex mean?
  • Unhandled Promise Rejection when trying to call…
  • Is it possible to apply CSS to half of a character?
  • How to enable Vue devtools in production mode for…
  • How can I pass a wct test while rearranging children…
  • How to Babel Transpile Object.entries/values in…
  • No 'Access-Control-Allow-Origin' header is present…
  • React after posting new password for user can't log in
  • Vue.js devtools not showing
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • during wct test: Failed to load resource: the server…
  • Mock MQRFH2 header in JUnit Testing Error [MQRFH2…
  • Error: Can't set headers after they are sent to the client
  • CORS GET returns an empty response body in Firefox
  • When I'm testing a web app by JUnit and Mockito I…
  • how to test express session
  • Any difference between await Promise.all() and…
  • Run chrome in fullscreen mode on Windows
  • SOLVED | (discord.py) Bot doesn't respond to any…
  • How to get a cross-origin resource sharing (CORS)…
  • aurelia-fetch-client create request headers on the fly
  • i am making a suggestion bot in discord.py. it runs…
  • How to use java.net.URLConnection to fire and handle…
  • Do you have to put Task.Run in a method to make it async?
  • Running parallel async tasks and return result in…
  • How to echo with different colors in the Windows…
  • Next.js dynamic api pages fail to respond to post…
  • Use a content script to access the page context…
  • Problems installing the devtools package
  • Issue adding access token to header in Backbone: It…
  • XMLHttpRequest cannot load ✘✘✘ No…
  • Why does Async.StartChild return `Async
  • What is the equivalent of node.js .getHeaders() in…
  • How to change the color of vaadin-select-text-field…
  • What does do?
  • Use Async/Await with Axios in React.js
  • How to use Servlets and Ajax?
  • Simple C example of doing an HTTP POST and consuming…
  • Passport.js in Next.js app not saving user across…
  • How can I resolve Web Component Testing error?
  • UnsatisfiedDependencyException: Error creating bean…
  • How to vertically align an image inside a div
  • Why am I getting "(304) Not Modified" error on some…
  • Codesandbox "Preview on edit" does not work for…
  • Jest spyOn call count after mock implementation…
  • Delay content of test of Cloud Functions with Mocha
  • When correctly use Task.Run and when just async-await
  • AngularJS $http, CORS and http authentication
  • Smart way to truncate long strings
  • vue-resource Headers from the cross-origin response…
  • Manually adding a Userscript to Google Chrome
  • How to enable CORS in ASP.net Core WebAPI
  • Aurelia with Typescript and async functions: this is…
  • Active tab issue on page load HTML
  • Stop the TypeScript definition wack-a-mole between…
  • Next JS build isn't building out every path
  • React-Query useQuery sending infinite fetch requests
  • Download file from an ASP.NET Web API method using AngularJS
  • Angular - Set headers for every request
  • How to make a SIMPLE C++ Makefile
  • What is causing this broken animation/transition in…
  • Continue fetching data until result is empty array
  • Can't mock function multiple times react, testing
  • Generate PDF with puppeteer without save it
  • Unexpected end of JSON input while parsing
  • Updating products with fetch and input value fields
  • Express/Typescript testing with Jest/Supertest
  • PolymerJS: Iron-Ajax - How to Bind Token to Headers…
  • await is only valid in async function
  • Accessing the web page's HTTP Headers in JavaScript
  • How does PHP 'foreach' actually work?
  • jQuery Mobile: document ready vs. page events
  • Making HTTP Requests using Chrome Developer tools
  • Axios is not sending cookies
  • how do i filter a data in quickmongoi so that it…
  • Python send POST with header
  • Can't specify the 'async' modifier on the 'Main'…
  • JavaScript ES6 promise for loop
  • Why is Vue.js Chrome Devtools not detecting Vue.js?
  • Super slow preflight OPTIONS in Chrome only
  • Discord bot in python asyncio
  • NextJS - Can you use a return from an api in a conditional?
  • How to support HTTP OPTIONS verb in ASP.NET…
  • How to fill out form in puppeteer
  • NextJs: Static export with dynamic routes
  • What is the JavaScript version of sleep()?
  • How can I use Promises in Aurelia?
  • 406 (Not Acceptable) when POSTing from Ember to DRF API
  • laravel vuejs/axios put request Formdata is empty
  • Sapper & Polka Authentication
  • CORS errors on Azure Translator API (Cognitive…
  • Chained await within a single async function
  • Is there any "font smoothing" in Google Chrome?
  • How to send file by email from Firebase Storage…
  • Node Js: Call async await within map not working
  • node express mongo API updating a record issue
  • Multiple API providers with nuxt-axios and a plugin…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I read CSV data into a record array in NumPy?

Next Post:

Does JavaScript have a method like “range()” to generate a range within the supplied bounds?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error