@ne_fe/koa-xml-body

koa middleware to parse xml request body

Usage no npm install needed!

<script type="module">
  import neFeKoaXmlBody from 'https://cdn.skypack.dev/@ne_fe/koa-xml-body';
</script>

README

koa-xml-body

Build Status npm version Dependency Status download times

Parse xml request body for Koa

Install

NPM

Usage

const koa = require('koa')
const xmlParser = require('koa-xml-body')

const app = koa()
app.use(xmlParser())

app.use(function(ctx, next) {
    // the parsed body will store in this.request.body
    // if nothing was parsed, body will be undefined
    ctx.body = ctx.request.body
    return next()
})

koa-xml-body will carefully check and set context.request.body, so it can intergate well with other body parsers such as koa-bodyparser:

// ...
const bodyParser = require('koa-bodyparser')

// ...
app.use(xmlParser())
app.use(bodyParser())

Note:

Current version (v2.x) of koa-xml-body is writtern with ES2015 and for koa@2. If you use koa@1.x, use koa-xml-body@1.x instead.

Options

  • encoding: requested encoding. Default is utf8. If not set, the lib will retrive it from content-type(such as content-type:application/xml;charset=gb2312).
  • limit: limit of the body. If the body ends up being larger than this limit, a 413 error code is returned. Default is 1mb.
  • length: length of the body. When content-length is found, it will be overwritten automatically.
  • onerror: error handler. Default is a noop function. It means it will eat the error silently. You can config it to customize the response.
  • xmlOptions: options which will be used to parse xml. Default is {}. See xml2js Options for details.
app.use(xmlParser({
    limit: 128,
    encoding: 'utf8', // lib will detect it from `content-type`
    xmlOptions: {
        explicitArray: false
    },
    onerror: (err, ctx) => {
        ctx.throw(err.status, err.message);
    }
}))

Licences

MIT