http – 使用Express提取POST数据

我读过node.js Extracting POST data.

但是这是我的问题,当我收到看起来像这样的HTTP请求时,如何用Express提取POST数据?

POST /messages HTTP/1.1
Host: localhost:3000 
Connection: keep-alive
Content-Length: 9
User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5 
Content-Type: application/xml 
Accept: */* 
Accept-Encoding: gzip,deflate,sdch 
Accept-Language: zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4 Accept-Charset: UTF-8,*;q=0.5 

msg=hello

我似乎无法通过Express获取身体外的msg = hello键值对.

我已经尝试了所有这些方法req.header()req.param()req.query()req.body但它们似乎是空的.

如何获取身体的内容?

app.post('/messages', function (req, res) {
    req.??
});
最佳答案
你的问题是bodyParser没有处理’application / xml’,我主要通过阅读这篇文章来解决这个问题:https://groups.google.com/forum/?fromgroups=#!topic/express-js/6zAebaDY6ug

你需要编写自己的解析器,我已经向github发布了以下更多细节:

https://github.com/brandid/express-xmlBodyParser

var utils = require('express/node_modules/connect/lib/utils', fs = require('fs'), 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(){  
        parser.parseString(buf, function(err, json) {
            if (err) {
                err.status = 400;
                next(err);
            } else {
                req.body = json;
                next();
            }
        });
    });
}

然后用它

app.use (xmlBodyParser);

转载注明原文:http – 使用Express提取POST数据 - 代码日志