【发布时间】:2020-09-10 22:09:30
【问题描述】:
我有如下表格。
<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>
“comment -post”类可以有多个表单。我想在表单提交上添加事件侦听器,以便请求类似于 ajax,如下所示。
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);
})
})
我的问题是如何将表单数据与我的 axios 请求一起提交。目前,没有发送表单数据。
我尝试了以下(已编辑),
function(e) {
e.preventDefault()
const formData = new FormData(e.target)
axios
.post(e.target.action, formData)
.then(res=>{
console.log(res)
})
.catch(console.error);
})
在节点js express服务器端,我正在做接收对象的控制台,看看数据是否已经真正通过了。
router.post('/comment/:post_id/', comment );
const comment = (req, res) => {
console.log(req.body)
res.json(req.body);
}
我在 req.body console.log 上没有看到“评论”
【问题讨论】:
标签: javascript ajax axios