Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

94
Visualizações
Displaying Fetch API response in browser window

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda