.text()
method returns a promise, resolving to the string corresponding to the raw response text decoded with UTF-8.
.json()
method returns a promise, resolving to the object received via parsing response. It is usually used when the content type of the response is "application/json"
Let's assume, that http endpoint returns text "hello world" as a response.
In that case .json()
will fail, because "hello world" can not be parsed as JSON.
In turn, if http endpoint always returns a json, for example: {"text":"hello world"}
, you can use both methods but results will be different. For example:
text
fetch(URL)
.then((result) => result.text())
.then((data) => {
console.log(data); // string `{"text":"hello world"}`
})
json
fetch(URL)
.then((result) => result.json())
.then((data) => {
console.log(data); // object {text:"hello world"}
})
P.S.
If you are always expecting response to be a json string and you need the field/values, there is no sense using .text()
plus JSON.parse(data)
because you can simply use .json()
to achieve same result.
Read more about response body methods text
and json
.