1

I was going through the docs of the Request interface in Fetch API https://developer.mozilla.org/en-US/docs/Web/API/Request

The example where we set the body does not seem to work. Tried on chrome dev console (version 84.0.4147.89) and also on firefox (84.0).

const request = new Request('https://example.com', {method: 'POST', body: '{"foo": "bar"}'});
console.log(request.url);
console.log(request.method);
console.log(request.body);

This results in,

https://example.com/
POST
undefined

What am I doing wrong here...?

EDIT:

The following is working,

request.json().then((j)=>{console.log(j)});

This leads me to believe that the body was set, but the getter is not working for some reason.

Can anyone shed light on what's going on?

  • Does this answer your question: https://stackoverflow.com/questions/27190447/pass-json-to-http-post-request – FelHa Dec 19 '20 at 19:56

1 Answers1

0

Try the following example:

const requestOptions = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        foo: 'bar'
    })
}
const response = await fetch('https://example.com', requestOptions)
const result = await response.json();
Or Assayag
  • 5,662
  • 13
  • 57
  • 93
  • This works, I'm able to make requests using `fetch(url, options)`, and is in fact what I ended up doing. But I was specifically wondering why the Request.body was not working as expected. – Raghuram Krishnaswami Dec 20 '20 at 18:10
  • `body` cannot accept `object` as value, so we need to convert `object` to `string` by `JSON.stringify()`. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch – Yu Miao Apr 09 '21 at 06:46