如何在提交侦听器上传递表单数据,以便 axios 可以发布表单数据?



我有一个如下所示的形式。

<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>

可以有多个带有"评论-帖子"类的表单。我想在表单提交中添加事件侦听器,以便请求类似于 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快速服务器端,我正在对收到的对象进行控制台,以查看数据是否已实际传递。

router.post('/comment/:post_id/', comment );
const comment = (req, res) => {
console.log(req.body)
res.json(req.body);
}

我在 req.body 控制台上看不到"评论.log

您需要使用事件的目标生成表单数据。所以你应该做:

const commentPostForms = document.querySelectorAll('.comment-post')
commentPostForms.forEach(form => {
form.addEventListener('submit', (e) => {
e.preventDefault()
const formData = new FormData(e.target);
axios
.post(e.target.action, formData)
.then(res=>{
console.log(res)
})
.catch(console.error);
})
})

此外,在您的 html 中将 enctype 设置为表单数据。因此,您将拥有:

<form class="comment-post" enctype="multipart/formdata" action="/api/v1/comment/<%= post._id %>">
<div class="comment-section">
<textarea rows="4" name="comment"></textarea>
<button type="submit" class="button">Submit</button>
</div>
</form>

如果您想检查他们是否真的存在您的表单数据。您可以在生成表单数据后执行以下操作:

for (let pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]); 
}

最新更新