如何让 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);
  });
view raw xmlBodyParser.js hosted with  ❤ by  GitHub

参考:

  • 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

猜你喜欢

转载自blog.csdn.net/dahuzix/article/details/79172704