当前这是我的有关向后端发送发布请求的代码(在使用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写错了,但我不知道该怎么做。有人可以纠正吗?
答案 0 :(得分:0)
您无法将对象附加到formData,而您可以在this answer上阅读更多内容。尝试
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)
...