I am trying to GET user listings from a node.js server with the fetch API, by POST’ing the json {pageNumber,UsersPerPage}. For that I have two buttons, that each POST their own text contents as pageNumbers to the server, when clicked. However, after iterating the two buttons 6 times the fetch API somehow fails. It does not fail if I click one button for consecutive times, but exactly when I switch between those two fetch POST requests exactly 6 times and the error message “Uncaught (in promise) TypeError: Failed to fetch at HTMLDivElement.” gets returned.
This is my frontend code:
side1.addEventListener('click',()=>{
fetch('/api/users/stats/side1/post',{
method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({
pageNum:side1.textContent,
userPerPage:userPerSide
})
});
fetch('/api/users/stats/side1/get').then(x=>x.text()).then(Txt=>{
display.innerHTML=Txt;
});
});
side2.addEventListener('click', ()=>{
fetch('/api/users/stats/side2/post',{
method:'POST' ,
headers:{'Content-Type':'application/json'},
body:JSON.stringify({
pageNum:side2.textContent,
userPerPage:userPerSide
})
});
fetch('/api/users/stats/side2/get').then(x=>x.text()).then(Txt=>{
display.innerHTML=Txt;
});
});
This is my backend – code:
var retVal;
app.post('/api/users/stats/side1/post',(req,res)=>{
if(req.body){
const {pageNum,userPerPage}=req.body;
retVal=GetPage(Number(pageNum),Number(userPerPage));
}
});
app.post('/api/users/stats/side2/post',(req,res)=>{
if(req.body){
const {pageNum,userPerPage}=req.body;
retVal=GetPage(Number(pageNum),Number(userPerPage));
}
});
app.get('/api/users/stats/side1/get',(req,res)=>{
res.send(retVal);
});
app.get('/api/users/stats/side2/get',(req,res)=>{
res.send(retVal);
});
I tried different header flags, like explicitly declaring Access-Control-Allow-Origin or no-cors and also async, await on the front-end. The bug occurs independently of the kind of content that gets returned by the server. I tried simplifying the code and changing the POST and GET urls for different html objects to avoid collisions. I was expecting for the fetch requests to be executed, without any sort of blocking. I already did search through the web as well as stackoverflow and while other questions sound familiar to this one, they are about a completely different problem, I think.
What I learned:
The problem does not occur, due to requests taking a bit too much time. And it is not due to Javascript being unable to interact with my server, since the first 5 requests work like expected and then the code breaks.
Bell Flo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.