I'm just learning nodejs but this bug kills me inside !! My website keeps requesting twice every Post method we have. At first, I thought it was my bad in connection with mongodb but I was wrong, this happens every POST method I have on my website (except login function).

Example: My comment function
Client-side
$('.commentSubmit').click(e => {
e.preventDefault()
let commentContent = $('#Comment').val()
let postId = $('#input-comment').val()
$.ajax({
url: '/dashboard/postComment',
type: 'POST',
data: {
postId: postId,
comment: commentContent
}
})
.done(data => {
let htmlcomment = `
<li class="list-group-item mt-3" id="${data._id}">
<h6 class="card-title" >${data.Owner}
<p class="card-text"><small class="text-muted">${data.createAt} </small></p>
</h6>
<h6 class="card-subtitle mb-2 text-muted"></h6>
<p class="card-text" >${data.content} </p>
<div class="card-footer text-muted" style="text-align: right;">
<button type="button" id="commentdelete" data-id="${data._id}" class="btn btn-danger btn-sm commentdelete">Delete</button>
</div>
</li>`
$(`ul#${postId}ulul`).prepend(htmlcomment)
document.getElementById('Comment').value = ''
})
})
Server
router.post('/postComment', (req, res) => {
console.log('done')
req.connection.setTimeout( 1000 * 60 * 10 )
if(req.session._id) {
if(!req.body.comment || !req.body.postId) {
return res.render('dashboard',{errors: 'Input comment first', user: u, posts: post, comments: comment, notifs: notif})
}
let comment = req.body.comment
let postId = req.body.postId
User.findOne({_id: req.session._id})
.then(u => {
user = u
})
console.log(req.url)
Posts.findOne({_id: postId})
.then(p => {
if(!p) res.send('PostID NOT Valid')
let comment = new Comments({
content: req.body.comment,
Owner: user.name,
PostId: postId
})
comment.save();
return res.json(comment)
})
} else {
return res.redirect('/login')
}
})
i think you have a form in your client side and a button with .commentSubmit class.
you trap the click event and try to prevent the default behavior. change the submit button type from submmit to button :
<button type="button">save</button>
so the button will not submit your form , but the js code will do the ajax post for you. the prevent default will work on form.sumbit event if you trap the form.onsubmit event.