Home > Enterprise >  How to read json response in Typescript
How to read json response in Typescript

Time:09-14

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);
    });

CodePudding user response:

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.

CodePudding user response:

The json method is available on the response object.

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

  • Related