trek-body-parser
v0.2.3
Published
Body parsing middleware
Downloads
2
Maintainers
Readme
body-parser
Body parsing middleware, supports json
text
raw
urlencoded
multipart
.
Based on raw-body, busboy, multer, qs.
Installation
$ npm install trek-body-parser --save
Examples
'use strict'
const Engine = require('trek-engine')
const bodyParser = require('..')
async function start () {
const app = new Engine()
app.use(bodyParser())
app.use(({req, res}) => {
res.body = req.body
})
app.on('error', (err, ctx) => {
console.log(err)
})
app.run(3000)
}
start().catch(err => console.log(err))
API
bodyParser(options)
json
urlencoded
is enabled by default.{ json: true, urlencoded: true, skip: false, // custom text: { ... }, ... }
.json(options)
{ detect: false, encoding: 'utf8', limit: '1mb', parse: JSON.parse, reviver: undefined, strict: true, type: [ 'application/json', 'application/json-patch+json', 'application/vnd.api+json', 'application/csp-report' ], transform(raw, { parse, reviver, strict }) { const empty = raw.length === 0 if (strict) { if (empty) return {} if (!STRICT_JSON_REG.test(raw)) { const err = new Error('Invalid JSON, only supports object and array') err.status = 400 throw err } } if (empty) return raw return parse(raw, reviver) } }
.text(options)
{ detect: false, encoding: 'utf8', limit: '1mb', type: 'text/plain' }
.raw(options)
{ detect: false, encoding: null, limit: '1mb', type: 'application/octet-stream' }
.urlencoded(options)
{ detect: false, encoding: 'utf8', limit: '56k', parse: qs.parse, type: 'application/x-www-form-urlencoded', transform(raw, { parse }) { return parse(raw) } }
.multipart(options)
Creates multer instance.
.any()
.array(fieldname[, maxCount])
.fields(fields)
fields
:[ { name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 } ]
.none()
.single(fieldname)
.busboy