Search code examples
node.jsexpressmultipartform-dataform-databody-parser

Why is formdata returning an empty object?


I am trying to send a formdata to my nodejs backend, but my backend prints out an empty object.

I want to send texts and picture using formdata

This is the frontend part of my code

  const formdata = new FormData();

  formdata.append("firstname", firstname);
  formdata.append('lastname', lastname);
  formdata.append('phone', phoneNumber);
  formdata.append('address', address);
  formdata.append('town', town);
  formdata.append('city', city);
  formdata.append('itLevel', itLevel);
  formdata.append('smartphone', smartphone);
  formdata.append('mapleOffers', mapleOffers);
  formdata.append('mapleColors', mapleColors);
  formdata.append('reason', reason);

  formdata.append("file", photoID.image, photoID.image.name.replace(/\s/g, ""));

  await Axios.post('/api/apply', formdata, {
    headers: {
      'Content-Type': 'application/json'
    }
  });

This is my backend (nodejs)

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const uploadFiles = require('./Utils/uploadFile');
var multer  = require('multer')
// var upload = multer({ dest: 'uploads/' })
var upload = multer()


const PORT = process.env.PORT || 3005;



app.use(bodyParser.json({limit: '50mb'}))
app.use(bodyParser.urlencoded({ extended: true, limit:'50mb' }))
app.use(upload.array('file')); 

app.use(express.static('client/build'));

app.post('/api/apply', uploadFiles('file'), async(req, res) => {

try {
    const uploadeFiles = req.uploadeFiles
    console.log(uploadeFiles)
    console.log(req.body);  //returns {}
    res.send('ok')
} catch (error) {
    console.log(error.message)
}
})

 app.listen(PORT);

Any help ??


Solution

  • const formdata = new FormData();
    

    Lets start with images

    formdata.append('image', imageFile);
    

    for text

    formdata.append('userName', 'Fred');
    

    then axios request

    axios({
    method: 'post',
    url: 'yoururl',   //addyoururl
    data: formdata,
    headers: {'Content-Type': 'multipart/form-data' }
    })
    .then(function (response) {
        //handle success
        console.log(response);
    })
    .catch(function (response) {
        //handle error
        console.log(response);
    });