中間件 ~ body-parser

最近一致在寫中間件,此次的目標是body-parser,哇咔咔, 模塊須要安裝的哦~javascript

body-parser應用

body-parser 能夠幫咱們解析請求體,假設寫一個請求java

client.jsnode

let http = require('http');


let client = http.request({
    hostname:'localhost',
    port:3000,
    path:'/',
    method:'post',
    headers:{
        'Content-Type':'application/x-www-form-urlencode'
    }
},function (res) {
});
client.end('name=zdl&age=9');
複製代碼

express.jsexpress

let express = require('express');
let app = express();
let bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended:true}))
app.post('/',function(req,res){
    console.log(req.body);
    res.end();
})
app.listen(3000)
複製代碼

解析後運行express.js node client.js,輸出{ name: 'zdl', age: '9' }app

body-parser的實現

urlencoded

let express = require('express');
let app = express();
let bodyParser = require('body-parser');
function urlencoded({extended}){
    return (req,res,next)=>{
        let buffers = [];
        req.on('data',function(data){
            buffers.push(data);
        })
        req.on('end',function(){
            let str = Buffer.concat(buffers).toString();
            if(extended){
                req.body = require('querystring').parse(str);
            }else{
                req.body = require('qs').parse(str); 
            }
            next()
        })
    }
}
app.use(urlencoded({extended:true}))
app.post('/',function(req,res){
    console.log(req.body);
    res.end();
})
app.listen(3000)
複製代碼

注: querystring不支持嵌套,故而有extended的區分post

text

text很簡單,可是有點小麻煩,由於假設用戶傳的是gbk格式,而 node又不支持這種格式,咱們須要用到iconv-lite庫轉碼(須要安裝),ui

  • 首先咱們須要將'Content-Type'格式轉換成'text/plain;charset=gbk'
  • 引用iconv-lite 傳輸數據
  • 安裝content-type包解析編碼格式
'Content-Type':'text/plain;charset=gbk'
 }
},function (res) {
});
let iconv = require('iconv-lite');
client.end(iconv.encode('我很帥','gbk'));
複製代碼

express.js編碼

function text(){
    return (req,res,next)=>{
        let buffers = [];
        req.on('data',function(data){
            buffers.push(data);
        })
        req.on('end',function(){
            let str = Buffer.concat(buffers);
            let contentType = require('content-type');
            let iconvLite = require('iconv-lite');
            let { parameters: { charset }, type} = contentType.parse(req.headers['content-type']);
            if(type === 'text/plain'){
                // 解碼操做
                req.body = iconvLite.decode(str, charset);
                console.log(req.body);
            }
            next()
        })
    }
}
app.use(text())
複製代碼

因此整個express.js文件以下url

let express = require('express');
let app = express();
let bodyParser = require('body-parser');
function urlencoded({extended}){
    return (req,res,next)=>{
        let buffers = [];
        req.on('data',function(data){
            buffers.push(data);
        })
        req.on('end',function(){
            let str = Buffer.concat(buffers).toString();
            if(extended){
                req.body = require('querystring').parse(str);
            }else{
                req.body = require('qs').parse(str); 
            }
            next()
        })
    }
}
app.use(urlencoded({extended:true}))
function text(){
    return (req,res,next)=>{
        let buffers = [];
        req.on('data',function(data){
            buffers.push(data);
        })
        req.on('end',function(){
            let str = Buffer.concat(buffers);
            let contentType = require('content-type');
            let iconvLite = require('iconv-lite');
            let { parameters: { charset }, type} = contentType.parse(req.headers['content-type']);
            if(type === 'text/plain'){
                // 解碼操做
                req.body = iconvLite.decode(str, charset);
                console.log(req.body);
            }
            next()
        })
    }
}
app.use(text())
app.post('/',function(req,res){
    console.log(req.body);
    res.end();
})
app.listen(3000)
複製代碼
相關文章
相關標籤/搜索