Problem with request in react and express.js

Viewed 142

so when i send a request which looks like that:

postman request

everythig in this api:

router.post('', async (req, res) => {
try {
if(!req.files || !req.body.format) {
  res.send({
    status: false,
    message: 'No file or format'
  });
} else {
  let uuidv4 = () =>{
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }
  let video = req.files.video;
  let video_name = uuidv4()
  let video_format = req.body.format

  if (allowedFormats.includes(video_format)) {
    let oldVideoPath = './public/uploads/' + video_name + "." + video_format
    const newVideoPath = './public/converted/' + video_name + ".mp3"

    let video_path = oldVideoPath
    video.mv(oldVideoPath)

    let proc = new ffmpeg({source: video_path, nolog: true})

    proc.setFfmpegPath("./ffmpeg/bin/ffmpeg.exe")
    proc
        .toFormat('mp3')
        .on('end', function () {
          res.send({
            status: true,
            message: 'File has been uploaded',
            file: newVideoPath.substring(1)
          });
        })
        .on('error', function (err) {
          res.send({
            status: false,
            message: 'An error occurred ' + err,
          });
        })
        .saveToFile(newVideoPath)
  } else {
    res.send({
      status: false,
      message: 'Wrong format!',
    })
  }
}
} catch (err) {
    res.status(500).send(err);
} 
});

works perfectly, but the second i send it from react

 const fileHandler = (file) => {
    const data = new FormData()
    data.append('file', file)
    data.append('format', baseFormat)
    fetch(process.env.REACT_APP_API_IP+'/upload-video', {
        method: 'POST',
        body: data
    })
        .then(response => response.json())
        .then(data => console.log(data))
}

it gives me an 500 (Internal Server Error). I checked and when sent from react the file and format reach the api but it breaks somewhere after the uuidv4 function.

Any help appreciated!

1 Answers

You should specify that it is form data.
Add to your fetch

headers: { 'Content-Type': 'multipart/form-data' },

Other issue is that express does not handle multipart/form-data by itself. You have to use some middleware like multer - https://github.com/expressjs/multer

Express part:

    const multer = require('multer');
    const upload = multer({ dest: "uploads/" });
    app.post("/upload-video", upload.single("video"), (req, res) => {
      let video = req.file
      // rest of your code
    }

And in you react code remember to use video field name:

 const fileHandler = (file) => {
    const data = new FormData()
    data.append('video', file)
    // ...
Related