如何解决axios发布请求正在发送Content-Type的请求标头:multipart / form-data导致未定义的req.body
我有一个使用axios发送帖子请求的表单。问题在于,正在使用Content-Type的标头发送请求:multipart / form-data。我的nodejs api不喜欢这样,给了我一个未定义的req.body。
我还有其他使用相同技术的表格,它们可以正常工作,并且标题与预期的一样:Content-Type:application / json; charset = UTF-8
正在发布Content-Type:multipart / form-data的表单没有任何图像。只是文本输入字段。
如果我尝试手动设置表单标题,则将其忽略。为什么一种形式发送标准的“ application / json”,另一种形式发送“ multipart / form-data”?
这是哈巴狗的形式:
form.form.form-send-cert-data
.form__group
label.form__label(for='name') Recipients Name
input#name.form__input(type='text',required,name='name')
.form__group
label.form__label(for='email') Recipient Email
input#email.form__input(type='text',name='email')
.form__group
label.form__label(for='plantId') Plant
select(name='plantId',id='plantId')
each val in ['5f1133ca79232fab1ffe5be4','5f113d3944221b47f577c239','5f113e019f4aa448a253ed87']
option=val
.form__group
label.form__label(for='message') Message
input#message.form__input(type='text',name='message')
.form__group.right
button.btn.btn--small.btn--green Send Certificate
这是我准备帖子的表单数据的方式:
addCertificateForm.addEventListener('submit',(e) => {
e.preventDefault();
const form = new FormData();
form.append('name',document.getElementById('name').value);
form.append('email',document.getElementById('email').value);
form.append('message',document.getElementById('message').value);
form.append('plantId',document.getElementById('plantId').value);
console.log('-Send Certificate-');
sendCertificate(form,'data');
});
这是sendCertificate.js:
import axios from 'axios';
import { showAlert } from './alerts';
export const sendCertificate = async (data,type) => {
console.log('sendCertificate.js');
try {
const url = '/api/v1/certificates/send';
const res = await axios({
method: 'POST',url,data,});
if (res.data.status === 'success') {
showAlert('success',`${type.toUpperCase()} sent successfully!`);
}
} catch (err) {
showAlert('error',err.response.data.message);
}
};
解决方法
由于您没有发送任何必须使用FormData发送的文件,因此您可以轻松地构建一个对象以传递给axios,该对象将作为json发送
addCertificateForm.addEventListener('submit',(e) => {
e.preventDefault();
const postData = {};
const keys = ['name','email','message','plantId'];
keys.forEach(k => postData[k] = document.getElementById(k).value)
sendCertificate(postData,'data');
});
请注意,我已经多年没有使用Axios了,不记得您是否需要设置json内容类型标头或默认情况下设置了
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。