req.body : 返回post請求中包含的數(shù)據(jù),默認(rèn)是 undefined岗仑,需要用body-parser進(jìn)行解析竹握。
post方法4種常見 Content-Type:
- application/www-form-urlencoded : 常用的表單發(fā)包方式
- multipart/form-data: 發(fā)送文件
- application/json : 用json格式發(fā)送數(shù)據(jù)(text/plain 將string轉(zhuǎn)成json)
- text/xml : 用xml格式發(fā)送數(shù)據(jù)(WeChat)
body-parser中提供4種解析方式
- bodyParser.json(options) //
- bodyParser.raw(options) //解析二進(jìn)制格式(buffer流數(shù)據(jù))
- bodyParser.text(options) //解析文本數(shù)據(jù)
- bodyParser.urlencoded(options) //解析utf-8的編碼的數(shù)據(jù)
options可選值中常用extended:當(dāng)設(shè)置為false時抖格,會使用querystring庫解析URL編碼的數(shù)據(jù)冕房,鍵值對中值為String或Array生逸;當(dāng)設(shè)置true時(默認(rèn))牢屋,會使用qs庫解析URL編碼的數(shù)據(jù),鍵值對的值為任何數(shù)據(jù)類型槽袄。
- 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);