Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch POST with formData is empty in Express JS route

I have a form that uses fetch() to AJAX with a route on NodeJS. When the AJAX POST hits the route, req.body shows an empty object {}.

Here's the code:

// in app.js

app.use(bodyParser.json());

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

// in form.js

form.getElementById('form__option').addEventListener('submit', e => {
    e.preventDefault()
    const form = $('form')[0]
    fetch('/polls/create', {
        method: 'POST',
        body: new FormData(form)
    })
})

// in appRoute.js

exports.createPost = (req, res, next) => {
    console.log('req body', req.body)
    res.send('NOT IMPLEMENTED: pollsController createPost');
}
like image 367
bresson Avatar asked Jan 21 '17 00:01

bresson


1 Answers

The issue here is that FormData will set the content type to be multipart/form-data, which Express' body-parser doesn't understand.

Note the comment here:

[body-parser] does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules: busboy and connect-busboy; multiparty and connect-multiparty; formidable; multer.

So in other words, you have to user a different module to handle the multipart body that FormData sends. I can recommend formidable, in which case you're server code would look something like:

const formidable = require('formidable')

exports.createPost = (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, (err, fields, files) => {
        console.log(fields)
        res.send('NOT IMPLEMENTED: pollsController createPost');
    }
}
like image 153
rmacqueen Avatar answered Nov 04 '22 14:11

rmacqueen