Search code examples
node.jsexpressclientbackendbody-parser

Request body is empty when posting form-data


I'm using a simple post request to my backend for a form data and for some reason the body is alwayes empty. I'm trying to isolate this so i changed the content type to application json and changed the data to json and only this way i can send data.

Client side:

submitForm(event) {
        event.preventDefault();
        console.log("gggg");
        const data = new FormData(event.target);

         axios.post("http://localhost:4000/user-form-post",data).then(function (response) {
            //handle success
            console.log(response);
        })
        .catch(function (response) {
            //handle error
            console.log(response);
        });

Server side:

// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({extended:true}));

app.use(express.urlencoded());

// Parse JSON bodies (as sent by API clients)
app.use(express.json());

app.use(logger('dev'));
app.post('/user-form-post', (req,res) =>{

    console.log("dfdf");
    console.log(req.body); // alwayes print empty dict {}
    res.end();

})

This is not working because it expects jsons(expected behavior):

// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({extended:true}));

Same behavior with Postman.


Solution

  • You will need to parse your form data from express side. For this you will have to use multer or multiparty. Try something like this. refer the documentation as well

    const multiparty = require('multiparty');
    
    app.post('/user-form-post', (req,res) =>{
    
       let form = new multiparty.Form();
    
       form.parse(req, function(err, fields, files) {
          Object.keys(fields).forEach(function(name) {
               console.log('got field named ' + name);
           });
       });
    })