Home > Net >  Displaying Fetch API response in browser window
Displaying Fetch API response in browser window

Time:11-24

I'm using the Fetch API to query some web services since I need to manually add X-Custom headers. All the examples I have found regarding displaying the result use console.log into the DevTools console window.

I have no JavaScript experience, but this was a means to an end, so I have:

fetch('<url>', {
    headers: myHeaders,
    method: 'GET',
    credentials: 'include'
}).then(
    function(response) {
        response.json().then(function(data)) {
            console.log(data);
        });
    })

This does display to console, but I'd like it in the browser window as if I had simply navigated to <url> and the response was displayed. Does JavaScript enable something like:

fetch('<url>', {
        headers: myHeaders,
        method: 'GET',
        credentials: 'include'
    }).then(
        function(response) {
            response.json().then(function(data)) {
                this.browserWindow.display(data);
            });
        })

How would I display it in the browser window as if I had navigated to the URL via the search bar?

Update

So I have been successful loading some results as so:

fetch('<url>', {
    headers: myHeaders,
    method: 'GET',
    credentials: 'include'
}).then(
    function(response) {
        response.text().then(function(data)) {
            document.querySelector('body').innerHTML = data
        });
    })

And the response appears for inspection; it is a JSON response so I was hoping response.Json() would work, but it just displays [object Object]. If I can figur eout how to "pretty display" the JSON, we have a solution.

CodePudding user response:

You have mostly figured it out, but if you can use JSON.stringify to get nicer formatting. For niceties, I wrapped the result in the HTML <pre> tag, but you can use whatever makes sense for your use case.

fetch('<url>', {
headers: myHeaders,
method: 'GET',
credentials: 'include'
}).then(
    function(response) {
        response.json().then(function(data)) {
            document.querySelector('body').innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`
        });
    })

There is a security caveat to be aware of. You are adding a response directly to the DOM without sanitizing the results, which can lead to XSS attacks (https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html) While this code is vulnerable, it is probably a minor threat, given your usecase.

For code utilized in production, there are a number of approaches to prevent this vulnerability, the most common being to escape any string you are going to insert into the DOM. An alternative is parsing the results, and creating the HTML elements you wish to insert, and using innerTEXT for the content provided from the API.

  • Related