node——post提交数据和使用express中body-parser

因为在post提交数据的时候,数据量可能会比较大,所以在获取用户的post提交数据时,是分多次提交的。所以我们应该将所有的数据收集完整,才开始对数据进行操作。

下面希望能收到一个对象,方法如下:

原生

  1. 监听request对象可以使用on()方法
fs.readFile(path.join(__dirname,'data','data.json'),'utf8',function(err,data){
        
        if(err&&err.code!=='ENOENT'){
            throw err;
        }
        
        var list=JSON.parse(data||'[]');

        //监听reqyest的对象的时候
        //声明一个数组,用来保存用户每次提交的数据
        var array=[];
        req.on('data',function(chunk){
            //此处的chunk参数,就是浏览器本次提交过来的一部分数据
            //chunk的数据类型是buffer
            array.push(chunk);
    
        });

        
    });

注意:这里接收是一段段的buffer类型的数据,将它们存储在一个数组中。

  1. 监听request对象的end事件,end事件触发,则数据提交完成
  • 将buffer数组合并为一条数据
  • 将buffer数据转化为字符串
  • 将字符串转化为json格式
 req.on('end',function(){
            //这个事件中将array数组中的每个buffer汇总起来成为一个buffer,在将buffer转化为字符串
            //然后字符串转化为json对象
            //不能直接用JSON.parse,因为现在字符串是这样的title=fff&url=ssss&text=isjsix
            var postBody=Buffer.concat(array);
            postBody=postBody.toString('utf8');
            
            postBody=querystring.parse(postBody);
            //postBody是对象了

上面需要注意 postBody=postBody.toString('utf8');后得到的字符串不能通过JSON.parse直接转化为json,title=fff&url=ssss&text=isjsix需要使用querystring.parse才行,querystring.parse能把一个 URL 查询字符串(str)解析成一个键值对的集合。

Express是基于NodeJs的Web框架,有很多中间件来处理某些响应以及给req,res添加了很多属性和方法。在前面使用原生的req.on和req.end时,要写不少代码,比较麻烦。在Express中可以使用body-parser中间件来简化刚才的过程。

body-parser的使用

npm install express body-parser

使用代码:

const express = require("express");
const bodyParser = require("body-parser");

// 创建服务
const app = express();

// 使用 body-parser 中间
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// 创建路由
app.post("/login", function (req, res) {
    console.log(req.body);
    res.send(req.body);
});

// 监听服务
app.listen(3000, function () {
    console.log("server start 3000");
});

当post请求时,body-parser会将数据转化为对象挂在req.body上,就不用我们自己从buffer转字符串,再转对象了。

[ 参考](https://segmentfault.com/a/1190000016707134)

posted @ 2019-09-06 17:26  ellenxx  阅读(3483)  评论(1编辑  收藏  举报