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

84
Visualizações
Appending fetched json data to a div

I have tried to create a client side function that sends a fetch request for json data and then appends the response to a div however it doesnt seem to be working.

here is the client side function code

function bobFun(){ 
  
  let response = fetch('http://127.0.0.1:3000/dylan/list', { mode: 'no-cors' })
    .then(console.log("fetch sent"))
    //.then(console.log(response))
    .then(response => {
  return response.text().then(text => {
    document.getElementById("test").append(text)
  });
});

here is the server side json data

let dylan = ['song recommendation 1',
  'song recommendation 2',
  'song recommendation 3',
];

app.get('/dylan/list', function(req, resp){
  resp.send(dylan);
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

I think the issue is the way you're using the first .then(). By just console logging you're not returning a value that can be chained with the next .then()

See my answer below and try reformatting yours to match.

fetch('https://jsonplaceholder.typicode.com/todos')
  .then(response => response.text())
  .then(text => {
     document.getElementById("test").append(text)
  })
<div id="test"></div>

over 4 years ago · Santiago Trujillo Relatório

0

I think you have not used then chaining correctly. In general then take callback function.

Below is right way of using fetch with then chaining -

function bobFun() {
   fetch('http://127.0.0.1:3000/dylan/list', {mode: 'no-cors'}).then(
     (response) => { 
       return response.text() ;
     }
   ).then( 
     (textData) => {
       document.getElementById("test").append(textData)
     }
   )
}


You can also use ECMAScript 2017 async/await instead of cumbersome then chaining with fetch which is having simple and clean sytanx.

async function bobFun() {
   const response = await fetch('http://127.0.0.1:3000/dylan/list', {mode: 'no-cors'})
   const textData = await response.text()
   document.getElementById("test").append(textData)
}
over 4 years ago · Santiago Trujillo 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