Main difference to regular Response
and Request
types is that no manual JSON.stringify
and headers.set('Content-Type', ...)
is required.
In my opinion, JSONRequest
is the most lightweight way of fixing the biggest issue of the Fetch API when dealing with JSON APIs, without resorting to full alternatives such as superagent or axios.
Example:
const response = await fetch(new JSONRequest('/comments', {
method: 'POST',
body: { text: 'Usage example: ...' },
}))
const { id } = await response.json()
The JSONResponse
type is mostly useful inside service workers when responding to requests with some ad-hoc JSON, or data stored in IndexedDD, but it can also be used to quickly put some data into a cache:
const cache = await caches.open('temp-comments')
cache.put('/comments/1', new JSONResponse({ text: 'Usage example: ...' }))
Note that both these classes only work with JSON as body. Use the base types when the body is a File
, ArrayBuffer
, etc.