formData is empty when I console.log it

194 views Asked by At

I want to upload image in my form but after sometime i get to know that in multipart/form-data I need to use formData. After using formData in my code I found out that the null values are sent in the database. Then I tried console.log to the formData and it is empty. I don't know what to do now.

Note: I have used multer in the backend to handle image uploads, so there isn't any problem in backend.

this is my handlesubmit

const handlesubmit = async (e) => {
    e.preventDefault();
    try {
      setshowloader(true);

      
      const data = {
        en_name: engName,
        hi_name: hiName,
        employeeID: EID,
        AadharNo: aadharNo,
        ContactNo: contactNo,
        employeeStatus: empStatus,
        address: address,
        city: city,
        state: state,
        designation: designation,
        employeeSalary: salary,
        Email: email,
        department: dept,
        joiningDate: joinDate,
        employeeType: emplType,
        BankName: bankName,
        BankBranch: bankBranch,
        IFSC_Code: bankIfsc,
        AccountNo: accNumber,
        AccountHolderName: accHolderName,
        employeePhoto: empPhoto,
    };
    
    const formData = new FormData();

    
    for (const key in data) {
      console.log(`Key: ${key}, Value: ${data[key]}`);
      formData.append(key, data[key]);
    }
    

      console.log(formData)

      serverInstance('hr/add-employee', 'post', formData).then((res) => {
        if (res?.status) {
          console.log(res.msg);
          setOpen(false);
          setshowloader(false);
          Swal.fire('Great!', res?.msg, 'success');
          handleClose();
        }
        if (res?.status === false) {
          console.log(res.message);
          setOpen(false);
          setshowloader(false);
          Swal.fire('Error', res?.msg, 'error');
        }
      });
    } catch (error) {
      console.log('catch' + error)
      Swal.fire('Error!', error, 'error');
    }
  };

this is my serverInstance

import { backendApiUrl } from '../config/config';

export const serverInstance = (path, method = 'get', payload, token) => {
  let headers = {
    'Content-Type': 'application/json', 
   
    Authorization: `Bearer ${sessionStorage.getItem('token')}`,
  };
  return new Promise((resolve, reject) => {
    let fetchOptions = {
      method,
      headers,
    };
    if (payload) fetchOptions.body = JSON.stringify(payload);
    fetch(backendApiUrl + path, fetchOptions)
      .then((res) => resolve(res.json()))
      .catch((err) => reject(err));
  });
};

The formdata isn't appending? or Do I need to do any other thing?

1

There are 1 answers

1
Stepan Michalek On

You cannot log a FormData object into the console.

Try formData.entries()

I think this is answered here.