8

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

1 Answer 1

8

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
});
Sign up to request clarification or add additional context in comments.

3 Comments

req.file still send undefined
Ah yes, I forgot the file input type acts a little differently. You must refer to Element.files[0]. I corrected my example so it works.
My pleasure :o)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.