NodeJS——Express Middleware : body-parser 与 req.body

req.body : 返回post请求中包含的数据,默认是 undefined,需要用body-parser进行解析。


post方法4种常见 Content-Type:

  1. application/www-form-urlencoded : 常用的表单发包方式
  2. multipart/form-data: 发送文件
  3. application/json : 用json格式发送数据(text/plain 将string转成json)
  4. text/xml : 用xml格式发送数据(WeChat)

body-parser中提供4种解析方式

  1. bodyParser.json(options) //
  2. bodyParser.raw(options) //解析二进制格式(buffer流数据)
  3. bodyParser.text(options) //解析文本数据
  4. bodyParser.urlencoded(options) //解析utf-8的编码的数据
    options可选值中常用extended:当设置为false时,会使用querystring库解析URL编码的数据,键值对中值为String或Array;当设置true时(默认),会使用qs库解析URL编码的数据,键值对的值为任何数据类型。
  • ex1
var express = require('express');
var bodyParser = require('body-parser');

var app = express();

var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({extended:false});

app.post('/home',urlencodedParser, function(req, res) {
    if(!req.body) return res.sendStatus(400);
    res.send('Welcome ' + req.body.username);
});

app.post('/about',jsonParser, function(req, res) {
    if(!req.body) return res.sendStatus(400);
    res.send('Welcome ~ ' + req.body.username);
})
app.listen(3000);

你可能感兴趣的:(NodeJS——Express Middleware : body-parser 与 req.body)