服务器处理 json 数据

今天作小程序后端,须要处理 json 数据,我用的 express 框架,没法直接处理,须要进行 json 提取,网上找了一堆,发现json 四种解析格式,在此记录一下html

  • www-form-urlencoded
  • form-data
  • application/json
  • text/xml

如下是四种格式处理方式,首先添加 Python 模块:express

1 var express = require('express');
2 var app = express();
3 var bodyParser = require('body-parser');

而后根据不一样格式处理:json

www-form-urlencoded:小程序

app.use(bodyParser.urlencoded({
    extended:true
}));
app.post('/urlencoded', function(req, res){
    console.log(req.body);
    res.send(" post successfully!");
});
app.listen(3000);

from-data:后端

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.post('/formdata',multipartMiddleware, function (req, res) {
  console.log(req.body);
  res.send("post successfully!");
});

application/json:微信小程序

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/urlencoded', function(req, res){
    console.log(req.body);
    res.send(" post successfully!");
});
app.listen(3000);

text/xml:微信

var express = require('express');
var bodyParser = require('body-parser');
var xml2json=require('xml2json');
var app = express();
app.use(bodyParser.urlencoded({
  extended: true
}));
app.post('/xml', function (req, res) {
  req.rawBody = '';//添加接收变量
  var json={};
  req.setEncoding('utf8');
  req.on('data', function(chunk) { 
    req.rawBody += chunk;
  });
  req.on('end', function() {
  json=xml2json.toJson(req.rawBody);
  res.send(JSON.stringify(json));
  }); 
});
app.listen(3000);

注:我在微信小程序用的是application/json的 post 请求,成功交互。app

谢谢此博客点击连接框架

相关文章
相关标签/搜索