0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.