trying to send multipart data [closed]

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

}


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.

1

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

*/

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật