-2

When I send the following request from my Chrome devtools

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: {
    title: 'foo',
    body: 'bar',
    userId: 1,
  },
  headers: {
    'Content-type': 'application/javascript',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));

This is the output I get:

{id: 101}

Which is not what I expect, in fact I expect

{title: 'foo', body: 'bar', userId: 1, id: 101}

that I get when I use Content-Type of 'aplication/json' like in the code below:

fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'POST',
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));
onepseudoxy
  • 580
  • 2
  • 8
  • 24

1 Answers1

0

So if you follow the documentation for the service you are using and POST some JSON and say it is JSON then the server-side code processes it as you expect.

… but if you disobey the documentation and post an object which the browser converts to the string [object Object] and (incorrectly) claim it is JavaScript then the server fails to process it.

This is normal behaviour and firmly in the "don't do that" category.


Aside: Allowing clients to post JavaScript programs which the server would (presumably) have to execute to do anything useful with would be extremely dangerous. This is a whole category of security problems which developers try to avoid, not encourage.

Doctor Doctor, it hurts when I do this! Don't do that.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335