skip to Main Content

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

2

Answers


  1. 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' };
    
    Login or Signup to reply.
  2. 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,
         contentType: "application/json",
     },
      redirect: 'follow'
    };
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search