【发布时间】:2020-04-22 03:15:44
【问题描述】:
目前这是我关于向后端发送 post 请求的代码(在 reactjs 中使用 axios):
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有什么用
-
我的后端代码只是从前端读取数据。但是,前端只发送[Object Object]。我读到 Formdata 发送密钥/对值集,但由于我的 Post 请求更复杂,它不适合吗?
标签: reactjs axios multipartform-data