Search code examples
reactjsfetchmultipartform-data

How To Send Object in Form Data in React.js


Actually i am sending a Form Data Which contains input text and input Files I am doing it like This but i am getting an empty object in response

Here is my Code

  const [ModelInfo,setModelInfo] = useState({
            title:"",
            description:"",
            category:""
    })

 const [Modelfile,setModelfile] = useState({
           file1:"",
           file3:"",
           file4:""
    })

Here Is My Fuction To Handle Submit

    e.preventDefault();

    const formData = new FormData();

     // My Post Files Object 

     for(let key in Modelfile){
        formData.append(key,Modelfile[key][0])
     }

     // My Post Text Object 

     for(let key in ModelInfo){
        formData.append(key,ModelInfo[key])
     }


    fetch("http://192.168.10.8:8300/createpost",{
        method:"POST",
        body:formData
    })
    .then((resp)=>{        
        resp.json().then((data) => {
            console.log(data)
        })
    })
Payload :
file1: (binary)
file3: (binary)
file4: (binary)
title: test
description: test
category: test

Preview : {}

Getting Empty Obj in response 

ScreenShot 1 Of Post Request

ScreenShot 2 Of Post Request


Solution

  • There are some possibilities that may cause the issue:

    1. Your headers are not set properly. Set Content-Type header to multipart/form-data or application/x-www-form-urlencoded when sending your data.

    2. On your server, you don't have body-parser or multer library. You should use this libraries (not together) in order to access your req.body and parse it.

    3. Maybe you forgot to add this config (in your index file in the root directory of the server):

    app.use(express.urlencoded({
        extended: true
    }))
    

    As a note, you can access your files with req.files in server and other fields with req.body.