将 post 带有图像的请求表单数据发送到后端

Send post request form data with image to back end

目前我的代码是关于向后端发送 post 请求(在使用 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)
...