本文介绍了Node.js Express express.json和express.urlen用表单提交编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Express(或Connect的)bodyParser中间件被标记为已弃用,建议用户改为使用:

Express (or Connect's) bodyParser middleware is marked deprecated and users are advised to use instead:

app.use(connect.urlencoded())
app.use(connect.json())

但是,当我从 Node.js in Action 中运行示例时,我使用curl来按照书中的建议填写表格:

However, when I run the an example from Node.js in Action, I use curl to fill out the form as suggested by the book:

curl -F entry[title]='Ho ho ho' -F entry[body]='santa loves you' http://abc:[email protected]:3000/api/entry

它不起作用.未定义req.body.我想念什么吗?它与bodyParser一起正常工作.

It doesn't work. req.body is not defined. Am I missing something? It works fine with bodyParser.

从Express 4开始的解决方案

以这种方式解析json:

Parse json this way:

var bodyParser = require('body-parser');

...

app.use(bodyParser.json());

以这种方式解析urlencoded正文:

Parse urlencoded body this way:

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

然后就没有弃用警告.扩展名:true(默认)使用qs模块,false使用querystring模块来解析正文.

Then there is no deprecation warning. The extended: true (default) uses the qs module and false uses the querystring module to parse the body.

请勿使用app.use(bodyParser()),该用法现已弃用.

Don't use app.use(bodyParser()), that usage is now deprecated.

推荐答案

bodyParser实际上是三个中间件的组成(请参见和相关源代码):jsonurlencodedmultipart:

bodyParser is in fact the composition of three middlewares (see documentation and relevant source code): json, urlencoded and multipart:

  • json解析application/json请求正文
  • urlencoded解析x-ww-form-urlencoded请求正文
  • multipart解析multipart/form-data请求正文,这就是您感兴趣的内容.
  • json parses application/json request bodies
  • urlencoded parses x-ww-form-urlencoded request bodies
  • and multipart parses multipart/form-data request bodies, which is what you're interested in.

如果仅指定jsonurlencoded中间件,则任何中间件都不会解析表单数据,因此不会定义req.body.然后,您需要添加一个中间件,该中间件能够解析表单数据,例如强大,busboy或多方(如 connect中所述的文档).

If you only specify json and urlencoded middlewares, the form data won't be parsed by any middleware, thus req.body won't be defined. You then need to add a middleware that is able to parse form data such as formidable, busboy or multiparty (as stated in connect's documentation).

以下是使用 multiparty 的示例:

Here is an example, using multiparty:

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.use('/url/that/accepts/form-data', multipartMiddleware);
app.post('/url/that/accepts/form-data', function(req, resp) {
    console.log(req.body, req.files);
});

别忘了通过使用这种中间件,任何人都可以将文件上传到您的服务器:这是您处理(和删除)这些文件的责任.

Don't forget that by using such middlewares you allow anyone to upload files to your server: it then your responsibility to handle (and delete) those files.

这篇关于Node.js Express express.json和express.urlen用表单提交编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:08