Uploading a file using "fetch" in reactJS

13,024

Finally I found the solution

I had to remove the 'Content-Type' from headers section and it worked out in nodejs using multer.

Using the "multipart/form-data"

'Content-Type': 'multipart/form-data'

requires us to set boundaries and hence it is throwing error at nodejs "Error: Multipart: Boundary not found"

Using the "application/x-www-form-urlencoded"

'Content-Type': 'application/x-www-form-urlencoded'

I am getting the req.body filled but as string but not able to access the individual values.

Hence final solution is removal of 'Content-Type'

Share:
13,024
Vara Prasad Boddu
Author by

Vara Prasad Boddu

Updated on June 11, 2022

Comments

  • Vara Prasad Boddu
    Vara Prasad Boddu almost 2 years

    Uploading a file using "fetch" in reactjs

    I am trying to upload a file using ReactJS.

    handleUploadfile = (event) => {
            event.preventDefault();
            const data = new FormData();
            data.append('photo',event.target.files[0] );
            data.append('name', 'Test Name');
            data.append('desc', 'Test description');
            fetch("http://localhost:3001/todo/upload", {
                 method: 'POST',
                 headers: {
                     'Accept': 'application/json',
                     'Content-Type': 'application/x-www-form-urlencoded'
                 },
                 body: data
            }).then((response) =>  {
               return response.text();
            })
        }
    

    For some reason I am not able read the files at nodejs(+multer) server using:

    req.files

    which shows "undefined" at post router.

  • Aflah vp
    Aflah vp about 2 years
    Removing 'Content-Type' from header worked for me