Freestyle09
Freestyle09

Reputation: 5508

How to post object using fetch with form-data in React?

I want to send a file to my express app as backend. My problem is that my body is send as type application/json and I want to send this as a form-data and later upload this file using multer -> https://github.com/expressjs/multer

I don't know how to prepare fetch call to get it later in express.

    fetch('/api/data', {
  method: 'POST',
  headers: {
    Accept: 'application/form-data',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
  .then((resp) => resp.json())
  .then((data) => console.log(data));

When I want to log req.file in api breakpoint I'm getting undefined.

app.post('/api/data', upload.single('cv'), (req, res) => {
  console.log(req.body);
  console.log(req.file);
  res.send({ name: 'Hello world!' });
});

I store react data from form using hooks and this object looks like this:

{
   name: 'test',
   surname: 'test2',
   cv: 'C:\\fakepath\\Babel error.png'
}

Upvotes: 8

Views: 28474

Answers (1)

Brian Emilius
Brian Emilius

Reputation: 729

You need to build your request body using the FormData API.

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".

const myFile = document.querySelector("input[type=file]").files[0];
const data = new FormData();
data.append("myFile", myFile);
data.append("otherStuff", "stuff from a text input");
fetch(target, {
    method: "POST",
    body: data
});

Upvotes: 8

Related Questions