Node JS body-parser-xml不工作

时间:2016-03-17 10:46:24

标签: javascript xml node.js loopbackjs body-parser

我想处理JSON和XML类型的请求,所以我在节点应用程序中使用body-parser-xml。

我的问题是第二个XML元素没有绑定到req.body,但我得到了第一个元素值。

我的代码是:

var loopback = require('loopback');
var boot = require('loopback-boot');
var cfenv = require('cfenv');
var bodyParser = require("body-parser");
var cookieParser = require('cookie-parser');
require('body-parser-xml')(bodyParser);

var app = module.exports = loopback();
var appEnv = cfenv.getAppEnv();

app.use(bodyParser.json());
app.use(bodyParser.xml({
    limit: '1MB', // Reject payload bigger than 1 MB 
    xmlParseOptions: {
        normalize: true, // Trim whitespace inside text nodes 
        normalizeTags: false, // Transform tags to lowercase 
        explicitArray: false // Only put nodes in array if >1 
    }
}));

app.use(bodyParser.urlencoded({
    "extended": true
}));

// boot scripts mount components like REST API
boot(app, __dirname);

app.start = function() {
    // start the web server
    return app.listen(process.env.PORT || 3000, function() {
        console.log("env port" + process.env.PORT);
        app.emit('started');
        var baseUrl = app.get('url').replace(/\/$/, '');
        console.log('Web server listening at: %s', baseUrl);
        if (app.get('loopback-component-explorer')) {
            var explorerPath = app.get('loopback-component-explorer').mountPath;
            console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
        }
    });
};

// start the server if `$ node server.js`
if (require.main === module) {
    app.start();
}

我的路线:

module.exports = function(app) {
    var router = app.loopback.Router();
    var User = app.models.pusers;
    var js2xmlparser = require("js2xmlparser");

    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        if (req.get("content-type") !== 'undefined') {
            if (req.get("content-type") == 'application/json') {
                res.setHeader('content-type', req.get("content-type"));
            } else if (req.get("content-type") == 'application/xml') {
                res.setHeader('content-type', req.get("content-type"));
            }
        }
        next();
    });

    app.middleware('initial', function logResponse(req, res, next) {
        res.on('finish', function() {});
        req.on('end', function(data) {});
        req.on('data', function(data) {
            // the request was handled, print the log entry
            console.log(req.method, req.originalUrl, res.statusCode);
            if (req.get("content-type") == 'application/xml') {
                console.log("xml data's :" + data);
            } else if (req.get("content-type") == 'application/json') {
                console.log("json data's :" + data);
            }
        });
        next();
    });

    function responseHandler(req, res, data) {
        if (req.get("content-type") == 'application/json') {
            return JSON.stringify(data);
        } else if (req.get("content-type") == 'application/xml') {
            return js2xmlparser("response", JSON.stringify(data));
        } else
            return data;
    }

    router.post('/login', function(req, res) {
        var response = {};
        console.log(req.body);
        console.log(req.body.username);
        try {
            User.find({
                where: {
                    name: req.body.username
                }
            }, function(err, data) {
                if (err) {
                    response = {
                        "error": true,
                        "message": "Error fetching data"
                    };
                } else {
                    if (data.length != 0) {
                        if (data[0].name == req.body.username && data[0].password == req.body.password) {
                            response = {
                                "error": false,
                                "data": "Success"
                            };
                        } else {
                            response = {
                                "error": false,
                                "data": "Password is incorrect"
                            };
                        }
                    } else if (data.length == 0) {
                        response = {
                            "error": false,
                            "data": "Username is incorrect"
                        };
                    }
                }
                console.log("Check login");
                res.end(responseHandler(req, res, response));
            });
        } catch (ex) {
            console.error("Error while retrive all data from User Model by name", ex);
            res.end(responseHandler(req, res, "Error while inserting User Model by name"));
        }
    });

    app.use(router);
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我发现如果将整个数据封装到单个XML标记中,则会收到完整的集合。例如:

<data>
  <username>somename</username>
  <password>passwd</password>
</data>

然后在node.js中访问它:

    req_xml = req.body["data"];
    console.log(req_xml["username"]);
console.log(req_xml["password"]);