Fetch POST with formData is empty in Express JS route

一曲冷凌霜 提交于 2020-12-30 11:51:45

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/41774334/fetch-post-with-formdata-is-empty-in-express-js-route

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