Sebastian Olsen Sebastian Olsen - 2 months ago 23
Node.js Question

How to get FormData in Express js?

I'm trying to upload a file to my express server. The client code looks like this:

axios.post('localhost:3030/upload/audio/', formData)


And in my express server:

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

App.post('/upload/audio/', function uploadAudio(req, res) {
let quality = ['320', '128'];
let file = req.body;

console.log(file)
res.send('Frick')
}


However, even though the mp3 file is sent:

http://i.imgur.com/bB7BofH.png

The
req.body
is empty when logged (note the empty object):

enter image description here

How can I get the formData (and file) in Express.js?

Answer

As @Tomalak said body-parser does not handle multipart bodies.

So you need to use some third party module I suggest use awesome module multer

I tried to do your code, hope it can help you

App.post('/upload/audio/', function uploadAudio(req, res) {
    var storage = multer.diskStorage({
        destination: tmpUploadsPath
    });
    var upload = multer({
        storage: storage
    }).any();

    upload(req, res, function(err) {
        if (err) {
            console.log(err);
            return res.end('Error');
        } else {
            console.log(req.body);
            req.files.forEach(function(item) {
                console.log(item);
                // move your file to destination
            });
            res.end('File uploaded');
        }
    });
});