reactjs - 将带有图像的发布请求表单数据发送到后端
问题描述
目前这是我关于向后端发送帖子请求的代码(在使用 axios 的 reactjs 中):
sendDataToBackEnd = async () => {
await axios.post(
'http://localhost:9000/message',
{
testPlace:
{
country: this.state.countryTest,
city: this.state.cityTest,
testSite: this.state.testSite
},
personalInformation:
{
name: this.state.name,
birthday:this.state.birthday),
gender:this.state.gender,
address:this.state.address,
}
}
,
{ headers: {
'Content-Type': 'application/json'
} }
).then((response) => {
// got the response. do logic
})
}
现在,我还需要将人的图像发送到后端进行保存。我想我必须发送表单数据。但是,我在将上面的信息发送到后端时遇到问题。这是我的做法:
sendDataToBackEnd = async () => {
let formData = new FormData();
formData.append('testPlace',
{
country: this.state.countryTest,
city: this.state.cityTest,
testSite: this.state.testSite
})
formData.append('personalInformation',
{
name: this.state.name,
birthday:this.state.birthday),
gender:this.state.gender,
address:this.state.address,
})
formData.append('file',this.state.picture)
await axios.post(
'http://localhost:9000/message',
formData
,
{ headers: {
'Content-Type': 'multipart/form-data'
} }
).then((response) => {
// got the response. do logic
})
}
但是,当我检查发送到后端的请求时,它显示 [Object Object]。我想我的 testPlace 和 personalInformation 的 formData 写错了,但我不知道该怎么做。任何人都可以纠正它吗?
解决方案
您不能将对象附加到 formData 您可以在此答案中阅读更多内容。试试这个
let formData = new FormData();
formData.append('file',this.state.picture)
formData.append('testPlace[country]', this.state.countryTest)
formData.append('testPlace[city]', this.state.cityTest)
formData.append('testPlace[testSite]', this.state.testSite)
formData.append('personalInformation[name]', this.state.name)
formData.append('personalInformation[birthday]', this.state.birthday)
formData.append('personalInformation[gender]', this.state.gender)
formData.append('personalInformation[address]', this.state.address)
...
推荐阅读
- junit - Mockito:将 InOrder 与间谍对象一起使用
- reactjs - 如何在 React js 中预填充表单 | 无法预先填写 react js 中的字段以进行编辑?
- c++ - 有没有办法在 C++ 中循环对象的不同数据成员
- javascript - 用于折叠 HTML 块的 Javascript 代码未运行
- c# - 从通用字符串中获取可能的字谜的数量,需要一个快速的解决方案
- symfony - Symfony 4 - 安全性 - 从多个防火墙相互共享上下文
- python - 如何通过 Python 脚本使用 ./ 执行命令行程序?
- angular - 使用 Angular 和 Ionic 上传大文件
- javascript - data-toggle="tab" 和 data-toggle="collapse" 不起作用
- javascript - 从 Promise 访问数据