Here is a form example:
<form class="comment-post" method="POST" action="/api/v1/comment/<%= post._id %>" enctype="multipart/form-data>
<div class="comment-section">
<textarea rows="4" name="comment"></textarea>
<button type="submit" class="button">Submit</button>
</div>
</form>
If there are multiple forms with the class 'comment-post', you can add an event listener for form submission to make an ajax request, like so:
const commentPostForms = document.querySelectorAll('.comment-post')
commentPostForms.forEach(form => {
form.addEventListener('submit', function(e) {
e.preventDefault()
axios
.post(this.action)
.then(res=>{
console.log(res)
})
.catch(console.error);
})
})
The issue is that no form data is being sent along with the axios request. To fix this, you can do the following:
function(e) {
e.preventDefault()
const formData = new FormData(e.target)
axios
.post(e.target.action, formData)
.then(res=>{
console.log(res)
})
.catch(console.error);
})
On the server side using Node.js and Express, you can log the received object from the form data:
router.post('/comment/:post_id/', comment );
const comment = (req, res) => {
console.log(req.body)
res.json(req.body);
}
However, if 'comment' is not appearing on the req.body in the console log, there might be an issue with how the form data is being passed.