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

req.body : 返回post請求中包含的數(shù)據(jù),默認(rèn)是 undefined,需要用body-parser進(jìn)行解析。


post方法4種常見 Content-Type:

  1. application/www-form-urlencoded : 常用的表單發(fā)包方式
  2. multipart/form-data: 發(fā)送文件
  3. application/json : 用json格式發(fā)送數(shù)據(jù)(text/plain 將string轉(zhuǎn)成json)
  4. text/xml : 用xml格式發(fā)送數(shù)據(jù)(WeChat)

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

  1. bodyParser.json(options) //
  2. bodyParser.raw(options) //解析二進(jìn)制格式(buffer流數(shù)據(jù))
  3. bodyParser.text(options) //解析文本數(shù)據(jù)
  4. 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);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容