res.data
set to null
, why is that?If the response cannot be parsed as the responseType
, then res.data
will be null
.
There are two common situations for this:
responseType: 'json'
. Empty strings are not valid JSON.responseType: 'json'
For example, some APIs will return plain text messages in the response body when there are errors, like the word "Error", rather than valid JSON.To resolve this, you can use the responseType
option to have greater control over the parsing of the response body from the server.
responseType
even an option?This option exists because of the inner workings of the fetch
API.
The argument that is passed to the .then()
callback of a fetch()
call is a Response object. The body of a Response object can only be read a single time, because it is a ReadableStream.
For bestfetch to reuse a response, it must pass the result of a single request to many "consumers," which are each of the individual calls to bestfetch.
If more than one "consumer" tried to read the body, then an error would be thrown. To get around this problem, bestfetch reads the body for you – one time – and passes that result to each consumer.