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

154
Visualizações
fetching promise breaks in setInterval

So i'm a student in computer science , i'm kinda newbie , i ran into a problem that i couldn't solve , so i want to fetch from my bdd mongo every x seconds , and show the result in the html. i have a function called getItems that does that for me , it works perfectly , hence when i try to set call it with setIntervel it works ! but only for 30 or 40 seconds and then breaks. this is my code :

setInterval(getItems , 1000 ) ; 


const getItems = async () => {
  const requestOptions = {
    method :'GET',
  };
  const response = await fetch('/user/listed', requestOptions);
  const response2 = await fetch('/user/me', requestOptions);
  items = await response.json(); 
  owned = await response2.json() ; 
   
  if (response.ok && response2.ok) {
    // delete all the old values in listed 
   var e =document.getElementById("listed") ; 
   var child = e.lastElementChild ; 
   while (child){
     e.removeChild(child) ; 
     child = e.lastElementChild ; 
   }
   // delete all the old values in boughts 
   var e2 =document.getElementById("bought") ; 
   var child2 = e2.lastElementChild ; 
   while (child2){
     e2.removeChild(child2) ; 
     child2 = e2.lastElementChild ; 
   }
    // adding new values 
    for (var key in items ){
     
      
      const node = document.createElement("li");
      const textnode = document.createTextNode(items[key].name + " : " + items[key].price);
      node.appendChild(textnode);
      node.setAttribute("id", items[key]._id)  ; 
      const buy = document.createElement("button") ; 
      const buytext = document.createTextNode("buy") ; 
      buy.setAttribute("id", items[key]._id) ; 
      buy.setAttribute("onClick" , "buy(this.id)")
      buy.appendChild(buytext) ; 
      node.appendChild(buy) ; 
      document.getElementById("listed").appendChild(node);


    }
    // adding new values 
    for (var o in owned.bought){
      
      const node = document.createElement("li");
      const textnode = document.createTextNode(owned.bought[o].name + " : " + owned.bought[o].price);
      node.appendChild(textnode);
      node.setAttribute("id", [o]._id)  ; 
      document.getElementById("bought").appendChild(node);
  }

  }
}

and here is a picture of the error : enter image description here

Thank you in advance !

here is my backend , the user/listed and user/me routes actually are :

module.exports.me =
  async (req, res) =>  {
    const user = await User.findById(req.userId);
    console.log(user);
    console.log(req.userId);
    res.status(200).json(user);
  }

  module.exports.listed =
  async (req, res) =>  {
    const listed = await Listed.find();
    console.log(listed);
    res.status(200).json(listed);
  }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are having cors errors, you said you have a node server? there is a cors modules try downloading it and installing it on your Node server. You should look into OWASP and CSP headers and their corresponding values

Also you may need to add headers to your requests:

require('dotenv').config();

app.use(cors());

app.use(middleware.setResponseHeaders)

app.use((req, res, next) => {
    res.append('Access-Control-Allow-Origin', ['*']);

 res.append('X-Content-Type-Options', 'nosniff');

 res.append(

 'Strict-Transport-Security',

 'max-age=31536000; includeSubDomains',

 );
 res.append('Referrer-Policy', 'no-referrer');

 res.append(

'Content-Security-Policy',

'default-src * data: blob: "self" wss:* ws:* https://*; script-src 
"unsafe-inline" "unsafe-eval" blob: data: "self"; style-src data: blob: 
"unsafe-inline" "self" https://*; connect-src data: blob: "unsafe- 
inline" "self" https://*;',

);
res.append(

'Authorization',

'Bearer bjhf86uygbiluhgvyujkilu8y79iyuygvuyili8ygvuybkuliygvu jkun87yuhygvuyjk78ygyuiyg9v8iubyuo8pyhguyvhbjhgyibhkjlnihjpup8hguyhbjhiygyuhioguhgybukhigyhbjhoyiguybkjhlihouighbkjnihugyhvbjnkjihbjnbhjnhbjnuh=',
);

next();

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