node.js - nodejs 怎么获取post请求的json数据
天蓬老师
天蓬老师 2017-04-17 11:56:02
0
5
559

url:http://127.0.0.1:3000/flow/save
[{
"mobile": "13444444444",
"mac": "30-3A-64-91-52-98",
"lastRefTime": 1438332288,
"up": 1111,
"down": 222
}]

服务器: app.post('/flow/save', traffic); 怎么获取Json数组

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

Antworte allen (5)
大家讲道理

res.body

    小葫芦

    呃,用的是express么?express的路由的话,可以在第二个参数里处理,比如这样:

    javascriptapp.post('/flow/save', require('body-parser').json(), traffic);

    如果你是非框架的话,那么应当自己接受到req后做处理,大致的流程是这样

    function parseJSON(req,res,next){ var arr = []; req.on("data",function(data){ arr.push(data); }); req.on("end",function(){ var data= Buffer.concat(arr).toString(),ret; try{ var ret = JSON.parse(data); }catch(err){} req.body = ret; next(); }) }

    就是简单的接收内容并且JSON.parse啦

      迷茫

      用 express 的中间件 body-parser

      var app = require('express')(); var bodyParser = require('body-parser'); var multer = require('multer'); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.use(multer()); // for parsing multipart/form-data app.post('/', function (req, res) { console.log(req.body); res.json(req.body); })

      同源的情况下,我用的是fetch

      var json = [{ "mobile": "13444444444", "mac": "30-3A-64-91-52-98", "lastRefTime": 1438332288, "up": 1111, "down": 222 }]; var data = JSON.stringify(json); fetch('http://127.0.0.1:3000/flow/save',{ method:'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body:data })

      非同源的情况下要'Content-Type': 'application/x-www-form-urlencoded' 的标准的编码格式
      然后把 json 转化为 FormData 对象
      就可以正常接收到 json

      不然 req.body 会一直是 {} 这样的空对象。

        PHPzhong

        非json数据怎么获取的它就怎么被拿到,无非是个数据格式的问题
        在服务端JSON.parse下就能叨叨JSON对象(包括数组)

          黄舟

          json本身就是字符串,只是不同语言可以把json字符串转化与自身相适应对象或者其他变量类型。

          一般都有:
          - 把json格式的字符串转化成xx
          - 把xx转化成json格式的字符串

          这里的xx就是上面的对象或者其他变量类型。

            Neueste Downloads
            Mehr>
            Web-Effekte
            Quellcode der Website
            Website-Materialien
            Frontend-Vorlage
            Über uns Haftungsausschluss Sitemap
            Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!