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数组
高洛峰2017-04-17 11:58:02
Um, are you using express? For express routing, it can be processed in the second parameter, such as this:
javascript
app.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
迷茫2017-04-17 11:58:02
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 {}.
PHPz2017-04-17 11:58:02
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
黄舟2017-04-17 11:58:02
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.