Express JS路由中的formData获取POST为空 [英] Fetch POST with formData is empty in Express JS route

查看:213
本文介绍了Express JS路由中的formData获取POST为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种使用fetch()到AJAX并带有NodeJS上路由的表单.当AJAX POST到达路线时,req.body将显示一个空对象{}.

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 {}.

代码如下:

//在app.js中

app.use(bodyParser.json());

app.use(bodyParser.json());

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

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

//在form.js中

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

//在appRoute.js中

// in appRoute.js

exports.createPost = (req, res, next) => {
    console.log('req body', req.body)
    res.send('NOT IMPLEMENTED: pollsController createPost');
}

推荐答案

此处的问题是 FormData 将内容类型设置为 multipart/form-data ,Express的 body-parser 不了解.

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

请在此处:

[body-parser]由于其复杂且通常较大的性质,因此无法处理多部分主体.对于多部分实体,您可能对以下模块感兴趣:busboy和connect-busboy;多方和连接多方;强大;摇摇欲坠.

[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.

因此,换句话说,您必须使用其他模块来处理FormData发送的多部分主体.我可以推荐 formidable ,在这种情况下,您的服务器代码应类似于:

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

这篇关于Express JS路由中的formData获取POST为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆