I implemented a timeout every 5 seconds to run location.reload() but on the pages I have some forms that send some post to mongoDB and once I do it, it will redirect me back to the page for the updates to be visible. The issue is that once is redirected the location.reload() will re send the post and create a new record in MongoDB. is there a way to avoid this?
This is an example of my code:
orders.js
...
if(ActionDOM == 'accept'){
FinalOrder.findOneAndUpdate({'_id':orderId},{
"$set": {
'orderStat':1,
'last_update':Date.now()
}
}).then(order => {
UpdateItem.aggregate([
{
$group:{
_id:'a',
minNum:{
$max:'$idUpdate'
}
}
}
]).then(u =>{
var idUpdate = (u.length==0)?1:u[0].minNum+1
const update = new UpdateItem({
idUpdate,
idUser:req.user._id,
idOrder:orderId,
orderStat:1
})
update.save().then(o =>{
Promise.all([mongoQueries.activeOrders(req.user._id.toString()),mongoQueries.menuItems(),mongoQueries.openOrders()]).then(info => {
res.render('openOrders', {pageTitle:'My orders', navBarOn:'1', user:req.user, info:info, refresh:1})
}).catch(e => console.log(e))
}).catch(e => console.log(e))
}).catch(e => console.log(e))
}).catch(e => console.log(e))
}
orders.ejs
...
<% if(locals.refresh){ %>
<% if(locals.refresh==1){ %>
<script>
setTimeout(location.reload(),5000)
</script>
<% } %>
<% } %>
...
location.reload() // it reloads page with post data.
Try
window.location = ""; // opens a page without post data
or
window.location = document.URL; // opens a current page without post data
<% if(locals.refresh){ %>
<% if(locals.refresh==1){ %>
<script>
setTimeout(function() {
window.location = "";
},5000)
</script>
<% } %>
<% } %>