Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
83
rated 0 times [  90] [ 7]  / answers: 1 / hits: 29326  / 6 Years ago, fri, march 2, 2018, 12:00:00

I tried to post form data to my express js server side. This is my pug file



form(action=/profile method=post enctype=multipart/form-data)
input(type=file accept=image/* name=profileimage)
input(type=text name=username)
input(type=submit value=Upload)


After that I tried to log the post data with req.body inside server side js as follow. That is my profile.js



router.post('/', function (req, res) {
console.log('Body- ' + JSON.stringify(req.body));
});


And this is my console result
body- {}



If I post without enctype=multipart/form-data like form(action=/profile method=post), I can get the post data from my console result.


More From » express

 Answers
6

You need to use a middleware to handle multipart form data, i think the most famous one is multer.


You can find it here: https://github.com/expressjs/multer


To use it:



  1. First add it to your modules with npm install --save multer in your root project



  2. Then import it in your .js file var multer = require('multer');



  3. Choose your upload directory by setting the dest argument in the multer constructor: var upload = multer({ dest: 'uploads/' });



  4. Now just pass it as a middleware in your POST function as follows:


    router.post('/', upload, function (req, res) {
    console.log('Body- ' + JSON.stringify(req.body));
    });



And don't forget to read the documentation at their github repo.


[#55030] Monday, February 26, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daveon

Total Points: 749
Total Questions: 108
Total Answers: 87

Location: Malaysia
Member since Wed, May 11, 2022
2 Years ago
;