Home > OS >  The request body contains invalid JSON - Node JS
The request body contains invalid JSON - Node JS

Time:01-11

I got error The request body contains invalid JSON, even my body was a valid JSON I use JSON.parse for converting my string to json here is my body

var formdata = JSON.parse('{"content":"this is a json sir"}') console.log(formdata) var requestOptions = { method: 'DELETE', body: formdata, headers: myHeaders, redirect: 'follow' }; and this my output on terminal still The request body contains invalid JSON :) output in the picture

CodePudding user response:

Instead of using JSON.parse() use JSON.stringify()

try this code.

var formdata = JSON.stringify({content: "this is a json sir" });

var requestOptions = {
  method: 'DELETE',
  body: formdata,
  headers: myHeaders,
  redirect: 'follow'
};

CodePudding user response:

By doing JSON.parse you are sending an object, not a JSON string which I believe is what it is expecting.

If you change it to the below, it should work as expected. You will need to send a header with content-type: application/json

var formdata = '{"content":"this is a json sir"}'
console.log(formdata) 
var requestOptions = { method: 'DELETE', body: formdata, headers: myHeaders, redirect: 'follow' };
  • Related