如何在Express中获取POST字段,而不使用bodyParser中间件? [英] How to get POST fields in Express, without using bodyParser middleware?

查看:206
本文介绍了如何在Express中获取POST字段,而不使用bodyParser中间件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用最新版本的Express,推荐(通过调试消息传递)是停止使用 bodyParser 中间件。我读了一下,它看起来像是bodyParser是 json urlencoded 中间件的包装器,并且看到,最新版本的Express(3.4.4)使用这些2而不是 bodyParser 开箱即用 - 对不对?



但现在,我不能到我的领域。 req.body 未定义。这是我的JS表单提交代码(只有文本字段,没有文件)。有人可以告诉我哪些属性/功能 req 是否可以使用这些值?

  var formData = new FormData($('#myForm')[0]); 
$ .ajax({
url:'/ myurl',
cache:false,
contentType:false,
processData:false,
data: formData,
type:'POST',
success:function(data){
console.log(data);
},
error:function(jqXHR, textStatus,errorThrown){
console.error('Error occurredured:'+ errorThrown);
}
});


解决方案

问题是,发送 FormData Content-Type 将是 multipart / form-data 。 / p>

虽然你使用 express.json() express.urlencoded() / code>,每个都只对特定的 Content-Type s - application / json application / x-www-form-urlencoded



Express / Connect将删除 multipart()的内置支持,并解析 multipart / form-data 将来由于安全性的考虑。而是推荐使用



所以,为了将来的支持通常,Express / Connect中的 FormData 多部分,则必须使用附加依赖关系。 p>

With recent versions of Express, the recommendation (conveyed through a debug message) is to stop using the bodyParser middleware. I read a bit, and it looks like bodyParser is a wrapper to the json and urlencoded middlewares - and lo and behold, the most recent version of Express (3.4.4) uses these 2 instead of the bodyParser out of the box - splendid, right?

But now, I can't get to my fields. req.body is undefined. Here's my JS form submission code (text fields only, no files). Could someone please tell me which property/function of req do I use to get at the values?

var formData = new FormData($('#myForm')[0]);
$.ajax({
    url: '/myurl',
    cache: false,
    contentType: false,
    processData: false,
    data: formData,
    type: 'POST',
    success: function(data) {
        console.log(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.error('Error occured: ' + errorThrown);
    }
});

解决方案

The issue is that, when sending FormData, the Content-Type will be multipart/form-data.

Though you're using express.json() and express.urlencoded(), each of them only acts on particular Content-Types -- application/json and application/x-www-form-urlencoded, respectively.

And Express/Connect will be removing built-in support for multipart() and parsing of multipart/form-data content in the future due to security concerns. They instead recommend using:

So, for future support of FormData and multi-part in general with Express/Connect, you'll have to use an addition dependency.

这篇关于如何在Express中获取POST字段,而不使用bodyParser中间件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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