简体   繁体   中英

How to implement New FormData() for Array data from Object to do the POST method using Axios, ReactJs?

On the backend I use multer to upload multiple files / images, I have tried using Postman and it works. but when i apply it on the frontend using reactjs, i am confused

sample case:

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":[{},{}]}
}

You can do the POST request through axios in this way:

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);
    });

Also its observed many times that localhost does not work with axios. Instead you need to use IP address. If suppose your IP address is 192.23.43.45 than URL becomes http://192.23.43.45:3000/api/v1/add . So, you can try this approach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM