Things have changed once again starting Express 4.16.0 , you can now use express.json()
and express.urlencoded()
just like in Express 3.0 .(事情已经改变 ,再次启动Express 4.16.0 ,您现在可以像Express 3.0一样使用express.json()
和express.urlencoded()
。)
This was different starting Express 4.0 to 4.15 :(从Express 4.0到4.15开始不同 :)
$ npm install --save body-parser
and then:(然后:)
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
The rest is like in Express 3.0 :(其余的就像在Express 3.0中一样 :)
Firstly you need to add some middleware to parse the post data of the body.(首先,您需要添加一些中间件来解析正文的帖子数据。)
Add one or both of the following lines of code:(添加以下一行或两行代码:)
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies
Then, in your handler, use the req.body
object:(然后,在您的处理程序中,使用req.body
对象:)
// assuming POST: name=foo&color=red <-- URL encoding
//
// or POST: {"name":"foo","color":"red"} <-- JSON encoding
app.post('/test-page', function(req, res) {
var name = req.body.name,
color = req.body.color;
// ...
});
Note that the use of express.bodyParser()
is not recommended.(请注意,不建议使用express.bodyParser()
。)
app.use(express.bodyParser());
...is equivalent to:(......相当于:)
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());
Security concerns exist with express.multipart()
, and so it is better to explicitly add support for the specific encoding type(s) you require.(express.multipart()
存在安全问题,因此最好显式添加对所需特定编码类型的支持。) If you do need multipart encoding (to support uploading files for example) then you should read this .(如果您确实需要多部分编码(例如,支持上传文件),那么您应该阅读此内容 。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…