问题
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