今天作小程序後端,須要處理 json 數據,我用的 express 框架,沒法直接處理,須要進行 json 提取,網上找了一堆,發現json 四種解析格式,在此記錄一下html
如下是四種格式處理方式,首先添加 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
謝謝此博客點擊連接框架