我马上进入正题。
我在 REACT 中有这个简单的表单。它有 2 个输入字段和 1 个图像上传字段。我需要将数据发送到使用Spring制作的后端API。
我现在正在尝试
const formID = document.getElementById('formGroup');
const formData = new FormData(formID);
fetch('api/5/add-image', {
method: 'POST',
body: JSON.stringify(formData),
headers: {
Authorization: 'Bearer ' + token,
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
}).then(res => {
this.setState({ isSubmitting: false });
console.log(res.text());
})
但我不断在控制台中收到相同的错误消息
所需的请求部分"file"不存在
有什么想法可能会导致问题吗?我认为身份验证 token 有效并且 header 没问题。
感谢您的宝贵时间:)
最佳答案
使用 FormData 和 fetch 时,不应将表单值字符串化,也不应指定 Content-Type header
这样就可以了
const formID = document.getElementById('formGroup');
const formData = new FormData(formID);
fetch('api/5/add-image', {
method: 'POST',
body: formData,
headers: {
Authorization: 'Bearer ' + token,
Accept: 'application/json',
}
}).then(res => {
this.setState({ isSubmitting: false });
console.log(res.text());
})
关于javascript - 我无法使用 REACT 中的 fetch 将图像上传到后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58934092/