bestfetch assumes that all requests return JSON responses. If you have an endpoint that returns something other than JSON, then you must use the responseType
option when calling bestfetch
to configure how it will be parsed.
responseType
The supported values for responseType
are all of the Body mixin methods:
"json"
: Returns the result of parsing the response text as JSON."text"
: Returns a string of the response body."formData"
: Returns a FormData object from the response body."blob"
: Returns a Blob from the response body."arrayBuffer"
: Returns an ArrayBuffer from the response body.For more information on these options, please reference the Body mixin documentation on MDN.
You may also pass a function as responseType
, which will be called with one argument, the response
. This allows you to inspect the response object before deciding how to parse it.
The following example would support an endpoint that returns JSON for every request except for when the status code is 400
.
bestfetch('/api/books/2', {
responseType(res) {
if (res.status === 400) {
return 'text';
} else {
return 'json';
}
}
})
.then(handlResponse);