-1

can anyone tell me exactly what text() do? I see people using it like that, and its working indeed:

    async getRandomNumber() {
        return await fetch(`${this.url}random`)
            .then((result) => result.text())
            .then((body) => {
                const data = JSON.parse(body);
                console.log(data);
            })
    }

The point is, without using text() I don't manage to get the data eventually but ending with a resolved promise

Darmon
  • 303
  • 4
  • 17
  • 2
    https://developer.mozilla.org/en-US/docs/Web/API/Body/text! – Bergi Jan 09 '20 at 14:48
  • This makes no sense. They should have used [`json`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json) instead. – Bergi Jan 09 '20 at 14:48
  • @Bergi, why not using text() if it save the overhead of looping and through the JSON data to build the HTML. it depends on the system you are working with and what data it provide. – ROOT Jan 09 '20 at 14:50
  • 2
    @mamounothman — They literally use `const data = JSON.parse(body);` as the very next thing. That's why they shouldn't use `text()`. – Quentin Jan 09 '20 at 14:53
  • Yeah, sorry I just noticed, you got me for that. – ROOT Jan 09 '20 at 14:54
  • @bergi but like Artem stated below, the JSON parse and text take the resolved promise and return a value – Darmon Jan 09 '20 at 15:31

2 Answers2

3

.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.

Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52
  • The example you gave me didn't work. I created an API which return {message: 'delayed by 10'} once I change text() to json, I recieve an error: "Unexpected token o in JSON at position 1" – Darmon Jan 09 '20 at 15:28
  • 2
    @Darmon, from what I see in your comment, the string you return is not a valid JSON, because all keys and string values must be in quotes ". Try to return `{"message":"delayed by 10"}` instead – Artem Arkhipov Jan 09 '20 at 15:37
  • I got you, thanks! – Darmon Jan 11 '20 at 14:41
2

Gets the resulting element as a text. There are other methods such as json() which is used to get response as JSON type. Look at fetch api docs for more info. https://developer.mozilla.org/en-US/docs/Web/API/Response

Ali Beyit
  • 431
  • 1
  • 6
  • 19
  • There is no info regarding my question in the link you provided. But only methods and properties regarding the responses of the API either by promise or syncly. The question is where the text() method came from, is it a node-fetch built in method or Javascript? since I am aware of it only from jQuery – Darmon Jan 09 '20 at 15:40
  • 1
    It is a method of fetch. If you looked carefully the page I sent there is a section called "methods" there you can see different methods you can apply on response you get by fetch. – Ali Beyit Jan 09 '20 at 15:43