1. 程式人生 > >如何讓 Node-express 支援 XML 形式的 POST 請求?

如何讓 Node-express 支援 XML 形式的 POST 請求?

express 是基於 connect 開發的,使用 bodyParser 對請求的包體進行解析,預設支援:application/jsonapplication/x-www-form-urlencoded, 以及 multipart/form-data。 也就是說不支援對 XML 形式的包體進行解析。

但是以 XML 格式作為介面資料交換還是有人在用,比如 Microsoft 的 Bing Translator HTTP API,以及騰訊微信的公眾平臺介面。之前用 Node.js 實現呼叫 Bing Translator 介面時用過 Node.js 的 xml2js 庫,可以把 XML 轉換成 JSON 格式以方便我們的程式進行解析。這裡我們同樣可以使用 xml2js 擴充套件 express 以使其支援 XML 形式的請求。

var express = require('express'),
var app = express();
var utils = require('express/node_modules/connect/lib/utils'), xml2js = require('xml2js');
function xmlBodyParser(req, res, next) {
if (req._body) return next();
req.body = req.body || {};
// ignore GET
if ('GET' == req.method
|| 'HEAD' == req.method) return next();
// check Content-Type
if ('text/xml' != utils.mime(req)) return next();
// flag as parsed
req._body = true;
// parse
var buf = '';
req.setEncoding('utf8');
req.on('data', function(chunk){ buf += chunk });
req.on('end', function(){
var parseString =
xml2js.parseString;
parseString(buf, function(err, json) {
if (err) {
err.status = 400;
next(err);
} else {
req.body = json;
next();
}
});
});
};
app.configure(function() {
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(xmlBodyParser);
});

參考:

  • https://gist.github.com/davidkrisch/2210498
  • http://expressjs.com/api.html#bodyParser
  • http://stackoverflow.com/questions/11002046/extracting-post-data-with-express
  • https://groups.google.com/forum/?fromgroups=#!topic/express-js/6zAebaDY6ug