skip to Main Content

I wanted to send the image array and form in react but my problem is it is showing the data in payload but when I debug in backend its body is empty
This is how I am sending data using api
Add a new cafe using multipart/form-data

  const api = createAuthAxios()

  try {
    // Ensure 'form' is a FormData object
    if (!(form instanceof FormData)) {
      throw new Error('Form data must be a FormData object.')
    }

    const response = await api.post('/cafes', form)
    return response.data // Return the response data directly
  } catch (error) {
    console.error('Error adding cafe:', error)
    throw error // Rethrow error to handle it in the calling function
  }
}```

this is my axis setup from where I am trying to create a custom header for the form-data 

```const createAuthAxios = () => {
  const token = localStorage.getItem('bearerToken')

  if (!token) {
    na
    console.error('No bearer token found')
    throw new Error('Bearer token is missing') // Throw error to handle token absence
  }

  return axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL, // Ensure VITE_API_BASE_URL is properly set in the env files
    headers: {
      Authorization: `Bearer ${token}`, // Use the token in the Authorization header
    },
  })
}```

this is my design for react this is how I am creating form data but the problem is it is sending I wanted to send the image array and form in react but my problem is it is showing the data in payload but when I debug in backend its body is empty this error. 

"Cannot convert object to primitive value"
 this is the error that is being responded and it is completely working on postman


 

const { register, handleSubmit, setValue, getValues, reset, control } = useForm({
defaultValues: {
name: ”,
location: {
address: {
street: ”,
suburb: ”,
state: ”,
postalCode: ”,
},
},
managedBy: ”,
timetable: [
{ day: ‘Monday’, openingTime: ”, closingTime: ” },
{ day: ‘Tuesday’, openingTime: ”, closingTime: ” },
{ day: ‘Wednesday’, openingTime: ”, closingTime: ” },
{ day: ‘Thursday’, openingTime: ”, closingTime: ” },
{ day: ‘Friday’, openingTime: ”, closingTime: ” },
{ day: ‘Saturday’, openingTime: ”, closingTime: ” },
{ day: ‘Sunday’, openingTime: ”, closingTime: ” },
],
images: [],
},
})

const { fields } = useFieldArray({
control,
name: ‘timetable’,
})

const [imagePreviews, setImagePreviews] = useState([])
const [users, setUsers] = useState([])

const submitForm = async (data) => {
try {
// Create FormData object
const formData = new FormData()

  // Append basic fields to FormData
  formData.append('name', data.name)
  formData.append('location[address][street]', data.location.address.street)
  formData.append('location[address][suburb]', data.location.address.suburb)
  formData.append('location[address][state]', data.location.address.state)
  formData.append('location[address][postalCode]', data.location.address.postalCode)
  formData.append('managedBy', data.managedBy)

  // Append timetable fields to FormData
  data.timetable.forEach((timetableItem, index) => {
    formData.append(`timetable[${index}][day]`, timetableItem.day)
    formData.append(`timetable[${index}][openingTime]`, timetableItem.openingTime)
    formData.append(`timetable[${index}][closingTime]`, timetableItem.closingTime)
  })

  // Append images (files) to FormData
  data.images.forEach((file) => {
    formData.append('images', file)
  })

  // Send FormData to the API
  const response = await add_cafe(formData)
  console.log('Cafe added successfully:', response.data)

  // Reset the form and clear previews on success
  reset()
  setImagePreviews([])
} catch (error) {
  console.error('Error submitting cafe:', error)
}

}


2

Answers


  1. Usually when encountering this issue, it’s because I forgot to include the body-parser lib:

    const express = require('express')
    const app = express()
    const port = process.env.PORT
    const bodyParser = require('body-parser')
    
    app.use(bodyParser.urlencoded({ limit: '15mb', extended: true }))
    app.use(bodyParser.json({ limit: '15mb' }))
    
    //Your endpoints here
    
    app.listen(port, () => `Server running on http://localhost:${port}`)
    

    You can read more here about how it works.

    Login or Signup to reply.
  2. Express has no built-in middleware to handle multipart/form-data, therefore the middleware multer may be a choice.

    The following sample code shows its usage.

    The sample is a node server. The testing code is also written in the server, just inside app.listen method.

    The way in which you have populated the formData object would remain the same. When multer is used, you would get the same data in the server as well. The req.body and the req.files are the two objects you would be able to refer for that. The sample code also shows the same with some dummy data.

    Please also note that the image files will be uploaded into the folder in the server as soon as the middleware has been run.

    server.js

    const express = require('express');
    const multer = require('multer');
    const upload = multer({ dest: 'uploads/' });
    
    const app = express();
    
    app.post('/addcafe', upload.any(), (req, res) => {
      // text data
      console.log(req.body.name);
      console.log(req.body.location.address.street);
      console.log(req.body.location.address.suburb);
      console.log(req.body.location.address.state);
      console.log(req.body.location.address.postalCode);
      console.log(req.body.managedBy);
      console.log(req.body.timetable[0].day);
      console.log(req.body.timetable[0].openingTime);
      console.log(req.body.timetable[0].closingTime);
    
      console.log(req.body);
    
      //image files
      req.files.forEach((file) => console.log(file));
    
      res.send('data uploaded successfully');
    });
    
    app.listen(3000, () => {
      console.log('L@3000');
      const formData = new FormData();
    
      // Append basic fields to FormData
      formData.append('name', 'data.name');
      formData.append('location[address][street]', 'data.location.address.street');
      formData.append('location[address][suburb]', 'data.location.address.suburb');
      formData.append('location[address][state]', 'data.location.address.state');
      formData.append(
        'location[address][postalCode]',
        'data.location.address.postalCode'
      );
      formData.append('managedBy', 'datamanagedBy');
    
      // Append timetable fields to FormData
      //data.timetable.forEach((timetableItem, index) => {
      const index = 0;
      formData.append(`timetable[${index}][day]`, 'timetableItem.day');
      formData.append(
        `timetable[${index}][openingTime]`,
        'timetableItem.openingTime'
      );
      formData.append(
        `timetable[${index}][closingTime]`,
        'timetableItem.closingTime'
      );
      //});
    
      // Append images (files) to FormData
      // data.images.forEach((file) => {
      formData.append('images', new Blob(['Some image content 1']));
      formData.append('images', new Blob(['Some image content 2']));
      formData.append('images', new Blob(['Some image content 3']));
      //});
    
      fetch('http://localhost:3000/addcafe', {
        method: 'POST',
        body: formData,
      })
        .then((response) => {
          if (!response.ok) {
            throw new Error(`Response status: ${response.status}`);
          }
          return response.text();
        })
        .then((json) => console.log(json))
        .catch((error) => console.log(error));
    });
    

    Test run

    node server.js

    Server console logs

    /*
    
    L@3000
    data.name
    data.location.address.street
    data.location.address.suburb
    data.location.address.state
    data.location.address.postalCode
    datamanagedBy
    timetableItem.day
    timetableItem.openingTime
    timetableItem.closingTime
    [Object: null prototype] {
      name: 'data.name',
      location: [Object: null prototype] {
        address: [Object: null prototype] {
          street: 'data.location.address.street',
          suburb: 'data.location.address.suburb',
          state: 'data.location.address.state',
          postalCode: 'data.location.address.postalCode'
        }
      },
      managedBy: 'datamanagedBy',
      timetable: [
        [Object: null prototype] {
          day: 'timetableItem.day',
          openingTime: 'timetableItem.openingTime',
          closingTime: 'timetableItem.closingTime'
        }
      ]
    }
    {
      fieldname: 'images',
      originalname: 'blob',
      encoding: '7bit',
      mimetype: 'application/octet-stream',
      destination: 'uploads/',
      filename: '4832597e91827bf67c409445a63d477e',
      path: 'uploads/4832597e91827bf67c409445a63d477e',
      size: 20
    }
    {
      fieldname: 'images',
      originalname: 'blob',
      encoding: '7bit',
      mimetype: 'application/octet-stream',
      destination: 'uploads/',
      filename: '005398a838dd9b558050d559cd03f83b',
      path: 'uploads/005398a838dd9b558050d559cd03f83b',
      size: 20
    }
    {
      fieldname: 'images',
      originalname: 'blob',
      encoding: '7bit',
      mimetype: 'application/octet-stream',
      destination: 'uploads/',
      filename: 'c88bc018f35d65c8b1dd895d548f9150',
      path: 'uploads/c88bc018f35d65c8b1dd895d548f9150',
      size: 20
    }
    data uploaded successfully
    
    */
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search