Cannot get the request body in the Backend

Viewed 23

Have created a FormData object without a form and append with two fields audio field which holds binary data and email field holding string data. When i use axios to send to this FormData object, its appended in the request body, but i cannot receive request body at the API side.

const email = 'test@gmail.com';
const url = 'http://localhost:3001/api/complaints/audio';
const sendData = () =>{
 let fd = new FormData();
 const audio = new Blob(audioData, { type: "audio/ogg; codecs=opus" });
 fd.append('audio' , audio);
 fd.append('email', email);

 const resp =  await axios.post(url, fd);
 console.log(resp);

API side.

// First middleware 
const { User } = require("../models/userSchema");

module.exports = async function (req, res, next) {
    console.log(req.body);
    const user = await User.findOne({ email: req.body.email });
    if (!user)
        return res.status(401).json({ error: "cannot perform such operation now" });

    next();
};

1 Answers

You need to use the 'Content-Type': 'multipart/form-data'~ header.

const sendData = () =>{
 let fd = new FormData();
 const audio = new Blob(audioData, { type: "audio/ogg; codecs=opus" });
 fd.append('audio' , audio);
 fd.append('email', email);

 const resp =  await axios.post(url, fd, {
   headers: {
     'Content-Type': 'multipart/form-data'
   }
 });
 console.log(resp);

Related