Express中间件body-parser简单实现上一篇写了如何使用body-parser中间件处理post请求。今天我们就粗略的实现一下body-parser中的urlencoded方法。首先在命令提示符下输入mkdirlib&&cdlib。然后输入touchbody-parser.js。在body-parser.js中键入以下代码。//lib/body-parser.jsconstquerystring=require('querystring');module.exports.urlencoded=function(req,res,next){letchunks=[];req.on('data',data=>{chunks.push(data);});req.on('end',()=>{//MergeBuffer.letbuf=Buffer.concat(chunks).toString();//在req.body上解析查询字符串json。req.body=querystring.parse(buf);next();});}下面是主要程序代码。//app.jsconstexpress=require('express');constbodyParser=require('./lib/body-parser');letapp=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/lanpangzhihttp://blog.langpz.com
