Search code examples
reactjsform-data

Pass object value in form data to API?


Here is the result of my backend API from POSTMAN:

I got two key here, which is jsonand also itemFile

enter image description here

   createItem(){

     const itemData = this.state;
     const selectedFile = this.state;

     const formData = new FormData();
        formData.append('json', itemData)
        formData.append('itemFile', selectedFile)

        console.log(formData)


        fetch(`http://localhost:9000/api/item/submit`, 
         {
             method: 'post',
             body: formData
         }).then ((result) => {  
                 let responseJSON = result;
                 console.log(responseJSON);
                 });
      }

After that, I got the error of Unrecognized token 'object': was expecting ('true', 'false' or 'null')\n at [Source: (String)\"[object Object]\"; line: 1, column: 8]

Is it I need to use JSON.Stringify? but how would I use it in form-data?


Solution

  • itemData in your code must be an object.

    FormData append method's second argument should be a USVString or Blob (including subclasses such as File).

    If none of these are specified the value is converted to a string by calling toString method.

    formData.append('json', itemData)
    
    formData.get('json')  // "[object Object]"
    

    So, you need to use JSON.stringify before appended to formData

    formData.append('json', JSON.stringify(itemData))