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

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数组

天蓬老师
天蓬老师

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

reply all(5)
大家讲道理

res.body

小葫芦

Um, are you using express? For express routing, it can be processed in the second parameter, such as this:

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

If you are a non-framework, you should handle it after receiving the req. The general process is as follows

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();
    })
}

Just simply receive the content and JSON.parse

迷茫

Use express middleware 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);
})

In the case of the same source, I use 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
    })

In the case of non-original sources, the standard encoding format of 'Content-Type': 'application/x-www-form-urlencoded' is required
and then convert json into a FormData object
and you can receive it normally json

Otherwise req.body will always be an empty object like {}.

PHPzhong

How to get non-json data? It’s nothing more than a data format issue
You can read JSON objects (including arrays) under JSON.parse on the server side

黄舟

Json itself is a string, but different languages ​​​​can convert json strings into objects or other variable types that suit themselves.

Generally available:
- Convert json format string into xx
- Convert xx into json format string

The xx here is the above object or other variable type.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template