首页 > 解决方案 > 如何为 Object 中的数组数据实现 New FormData() 以使用 Axios、ReactJs 执行 POST 方法?

问题描述

在后端,我使用 multer 上传多个文件/图像,我尝试使用 Postman 并且它可以工作。但是当我使用reactjs在前端应用它时,我很困惑

示例案例:

state = {
  name: 'product1',
  price: '200',
  images: [{name: "1.png", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924},
            {name: "2.png", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924}],
  files: [{name: "1.zip", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924},
            {name: "2.zip", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924}],
          
}

handleSubmit = () => {
  const { name, price, images, files} = this.state

  const body = new FormData()
  body.append('name', name)
  body.append('price', price)

  images.map((file, i) =>  body.append('images[i]', file[i])) // not work
  files.map((file, i) =>  body.append('files[i]', file[i])) // not work

  axios.post(`http://localhost:3000/api/v1/add`, body)
  .then((res) => res.data.data)

  // result {"name":"roduct1","price":"200","images":[{},{}],"files":[{},{}]}
}

标签: javascriptreactjsexpressaxiosmulter

解决方案


可以这样通过 axios 发出 POST 请求:

var bodyFormData = new FormData();
bodyFormData.set('userName', 'Fred');
bodyFormData.append('image', imageFile); 

axios({
    method: 'post',
    url: 'myurl',
    data: bodyFormData,
    headers: {'Content-Type': 'multipart/form-data' }
    })
    .then(function (response) {
        //handle success
        console.log(response);
    })
    .catch(function (response) {
        //handle error
        console.log(response);
    });

它还多次观察到 localhost 不能与 axios 一起使用。相反,您需要使用 IP 地址。如果假设您的 IP 地址192.23.43.45比 URL 变为http://192.23.43.45:3000/api/v1/add. 所以,你可以试试这个方法


推荐阅读