3

I'm new on Typescript

How can I read the function json response from my callback function?

this is my function, it return html content...

async function getContent(src: string) {

    try {
        const response = await fetch(src);

        if (!response.ok) {
          throw new Error(`Error! status: ${response.status}`);
        }

        const result = { content: await response.text(), correlationId: response.headers.get("x-correlationid") };
        return result;
    } catch (error) {
        if (error instanceof Error) {
            return error.message;
        } else {
            return 'An unexpected error occurred';
        }
    }
}

And this is the way I'm trying to read the json from response. But result.json() is highligthed in red with error "Property json does not exists on type string"

getContent(src)
        .then( result => result.json())
        .then( post => {
            iframe.contentDocument.write(post.content);
        })
        .catch( error => {
            console.log(error);
        });

***** UPDATE ******

The problem was inside my getContent function, the catch block must return errors in the same object structure.

function updated

async function getContent(src: string) {

    try {
        const response = await fetch(src);

        if (!response.ok) {
          throw new Error(`Error! status: ${response.status}`);
        }

        const result = { content: await response.text(), correlationId: response.headers.get('x-correlationid') };
        return result;
    } catch (error) {
        if (error instanceof Error) {
            return { content: error.message, correlationId: undefined };
        } else {
            return { content: 'An unexpected error occurred', correlationId: undefined };
        }
    }
}

and the function call

getContent(src)
    .then( result => {
        iframe.contentDocument.write(result.content);
        console.log(`I have the correlation ${result.correlationId}`);
    })
    .catch( error => {
        console.log(error.content);
    });
Cristobal BL
  • 103
  • 3
  • 11
  • 1
    Why not just use `await response.json()` instead of `await response.text()` ? – Obie Sep 13 '22 at 16:48
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Tibrogargan Sep 13 '22 at 16:50
  • @Tibrogargan OP seems to know how. – gre_gor Sep 13 '22 at 16:51
  • 1
    `getContent` either returns an object or a string, if there's an error. None of those have a ˙json˙ method. It doesn't return the response object from `fetch`, which you seem to assume. – gre_gor Sep 13 '22 at 16:53
  • 1
    The Response object's `text()` method is also async, so calling `await` on it is fine. The issue is that the object being returned does not have a `.json()` method. – Tibrogargan Sep 13 '22 at 17:01
  • @Tibrogargan I agree. This is obviously the reason. Removing the line in which OP is trying to call `.json()` on the return value of `getContent` will also be fine because one can only write strings in a document anyway – tabulaR Sep 13 '22 at 17:06

2 Answers2

3

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#body

you can see what methods exists out of the box on a the response object the fetch method returns. You are currently using the text method which extracts the body content as text. You probably want to remove the line in which you are calling json on the response because the write method on the document of the iframe can only consume strings anyway:

getContent(src)
    .then( post => {
        iframe.contentDocument.write(post.content);
    })
    .catch( error => {
        console.log(error);
    });

In a nutshell: the .json method does not exist on the object your getContent function returns. You can run JSON.parse on the content but as I explained above you should apply the json method on your response.

tabulaR
  • 300
  • 3
  • 13
  • 1
    what is the reason for the downvote. OP is obviously trying to call a method that doesn't exist on the object his function is returning. – tabulaR Sep 13 '22 at 17:01
  • If I had to guess it's because both `.json()` and `.text()` both return a representation of the response body, but your answer implies that `.json()` is somehow preferred. There was no need for the `.then()` chain at all. If the response body is not `application/json`, `.json()` is not useful. – Tibrogargan Sep 13 '22 at 17:08
  • @Tibrogargan This is what I also answered on your comment above. He was asking specifically for the json method and I was not reading what was consuming the `post.content`. So you are right. – tabulaR Sep 13 '22 at 17:11
  • 1
    thank you @tabulaR, you were right, the problem was into my function, exactly the catch, just had to return errors in the same object structure as my result. Updating my question.... – Cristobal BL Sep 13 '22 at 18:42
0

The json method is available on the response object.

In getContent you are setting the content property to be a string.

moy2010
  • 854
  • 12
  • 18