'How to send a image jpg/png file from react to express server

I am trying to send an object from react to express server using node.js

this is my object:

const formData = {
    location: location,
    cost: cost,
    email: email,
    image: image,
  };

This is my fetch post method :

fetch("http://localhost:5000/places", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify(formData),
})
  .then((res) => res.json())
  .then((data) => {
    if (data.insertedId) {
      alert("Plcae added successfully");
    }
  })
  .catch((error) => {
    console.error("Error:", error);
  });

I can see the image file object in client site console but I am not getting that in expreess server.



Solution 1:[1]

You have to send your input data as FormData to share images/files to the backend.

function uploadImage() {
  let formData = new FormData(yourFormData);
  fetch("http://localhost:5000/places", {
    method: "POST",
    body: formData,
  }).then((res) => res.json())
  .then((data) => {
    if (data.insertedId) {
      alert("Plcae added successfully");
    }
  })
  .catch((error) => {
    console.error("Error:", error);
  });
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mchowdam