1

I am using node, express, html and i am trying to post a to my server side using a html form. The problem is I get {} as my req.body.

My html form is the following:

    <form method = 'post' action='get_name' enctype="multipart/form-data">
      <input type="text" name="form_name"><br>
      <input type="submit" value="Upload name">
    </form>

I use the following in the begining of the my node.js file:

app.use(bodyParser.urlencoded({limit:'5mb', extended:false}));
app.use(busboy());

My app.post is the following:

app.post('/get_name',function(req, res, next){
        console.log("the name of the form is : ", req.body);
        res.redirect('/admin');
});

When i am trying to get req.body.form_name I get undefined. I cant find out what is wrong with my code. Any suggestions are welcome. :)

cs04iz1
  • 1,737
  • 1
  • 17
  • 30

3 Answers3

5

If you're going to use busboy, you should follow the documentation:

https://github.com/mscdex/busboy

Otherwise, bodyParser() does not support multi-part form data. I personally recommend this library for it's simplicity:

https://www.npmjs.com/package/multer

This will populate req.body the way you are intending to use it.

sctskw
  • 1,588
  • 1
  • 12
  • 14
  • 1
    since bodyParser() does not support multi-part form data, if you want to populate req.body, try using this library:https://www.npmjs.com/package/multer .. I personally use this over other options because of it's simplicity – sctskw Mar 11 '15 at 16:05
0

Use connect-multiparty module for multipart/form-data and add that in middleware of API route.

let multipart = require('connect-multiparty');
let multipartMiddleware = multipart();

 router.route('/customer').post(validate(validations.customerValidation.registerCustomer),multipartMiddleware,CONTROLLER.CustomerBaseController.registerCustomer);

It is working on my side.

Udit Kumawat
  • 654
  • 1
  • 8
  • 21
-3

Try this:

app.post('/get_name',function(req, res, next){
        console.log("to name of the form is : ", req.param('form_name'));
        res.redirect('/admin');
});
Tom Hallam
  • 1,924
  • 16
  • 24
  • Might be worth `console.log()`ing your `req.params` above that other `console.log`, see if you can spot the correct info in there. – Tom Hallam Mar 11 '15 at 15:06