Re: [whatwg/fetch] Proposal: `Response.json` helper (Issue #1389)

it's also very common to post json to a rest api as well...
so how about something json-ish for Request as well while we are at it if we are going to have something for Response?

Today i just created a simple helper function to convert object into a blob and use that as a body instead, find it more easier than setting headers by myself. just let the fetch set the content-length & content-type header for you... works well for POJO Response stuff too.

```js
const toJSON = obj => new Blob([ JSON.stringify(obj) ], { type: 'application/json' })

new Response(toJSON({ a: 1 }))

fetch('/', {
  body: toJSON({ a: 1 })
})
```
conclusion: we need `Blob.fromJSON({ a: 1 })` 💥 

---

no but seriously... i think that fetch should be smart enough to be able to figure out if the body is a plain object then it should just simply serialize it for you... so you can just do:
```js
fetch('/', {
  body: { a: 1 }
})
// and
new Response({ a: 1 })
new Request('/', { method: 'post', body: { a: 1 } })
```
it is so so common to see higher lever of abstraction of this...
examples:
- `axios.post('https://httpbin.org/post', { answer: 42 })`
- `superagent.post('/api/pet').send({ name: 'Manny', species: 'cat' })`
- `await got.post('https://httpbin.org/anything', { json: { hello: 'world' } }`
- `require('simple-get')({ url, method: 'POST', body: { key: 'value' } })`

almost each and every other user-land http library deal with json somehow, but not fetch...

it feels very pointless that `await new Response({ a: 1 }).text() === '[object Object]'` i think we can do better.

-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/fetch/issues/1389#issuecomment-1035433711

You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/fetch/issues/1389/1035433711@github.com>

Received on Thursday, 10 February 2022 20:01:04 UTC