zweizhao.github.io

项目,文章,随笔,博客,Markdown,个人网站,人生感悟。

View on GitHub
var express = require('express'),
var app = express()

var utils = require('express/node_modules/connect/lib/utils'), xml2js = require('xml2js')

function xmlBodyParser(req, res, next) {
    // GET 参数直接 req.query 获取

    if (req._body) return next()
    req.body = req.body || {}

    // 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)
})