Home > Software design >  Appending fetched json data to a div
Appending fetched json data to a div

Time:03-31

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

CodePudding user response:

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>

CodePudding user response:

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)
}
  • Related