Express中间件body-parser简朴完成

Express中间件body-parser简朴完成

之前文章写了怎样用body-parser中间件处置惩罚post要求,本日就也许完成下body-parser中urlencoded 这个要领。
起首经由过程敕令提醒输入 mkdir lib && cd lib。
再输入touch body-parser.js。
把下面的代码在body-parser.js 敲一遍。

// lib/body-parser.js
const querystring = require('querystring');

module.exports.urlencoded = function (req, res, next) {
    let chunks = [];
    req.on('data', data => {
        chunks.push(data);
    });

    req.on('end', () => {
        // 兼并Buffer。
        let buf = Buffer.concat(chunks).toString();
        // 把querystring剖析过的json 放到 req.body上。
        req.body = querystring.parse(buf);
        next();
    });
}

下面是主程序代码。

// app.js
const express = require('express');
const bodyParser = require('./lib/body-parser');

let app = express();

app.use(bodyParser.urlencoded);


app.post('/', (req, res) => {
    res.send(req.body);
});

app.listen(8000);

如今就完成和body-parser中间件相似的功用了,req.body上面有要求过来的post数据。

我的博客和github,喜好就去点点星吧,感谢。

https://github.com/lanpangzhi

http://blog.langpz.com

    原文作者:lanpangzhi
    原文地址: https://segmentfault.com/a/1190000018829159
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞