html multipart/form-data error in req.body using node/express

时光怂恿深爱的人放手 提交于 2021-02-08 06:52:39

问题


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. :)


回答1:


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.




回答2:


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.




回答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');
});


来源:https://stackoverflow.com/questions/28989485/html-multipart-form-data-error-in-req-body-using-node-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!