Ashutosh Dubey
Ashutosh Dubey

Reputation: 31

How to send file + JSON in single request from react to nodejs

I'm working on my personal ecommerce project where in seller page I'm adding product information such as Name, Category, description, price and image. I want to send this all data to backend to express server and store into postgresql. If any idea how to send image file and other text type data in single request please do tell.

Thankyou.

Upvotes: 2

Views: 131

Answers (1)

Jaffar Javeed
Jaffar Javeed

Reputation: 21

Please use FormData to post the data as shown in the example below

const images = document.getElementById('imageControl');
const name = document.getElementById('nameControl');
const category = document.getElementById('categoryControl');
const description = document.getElementById('descriptionControl');
const price = document.getElementById('priceControl');
var formData = new FormData();
formData.append("Name", name);
formData.append("Category", category);
formData.append("Description", description);
formData.append("Price", price);
formData.append("Image", images.files[0]);
const response = await fetch('url', {
  method: 'POST',
  headers: { 'Content-Type': 'multipart/form-data' },
  body: formData
});

Upvotes: 1

Related Questions