1.0.1 • Published 10 years ago
middleware-json-parse v1.0.1
middleware-json-parse 
JSON parsing middleware.
Features:
- fast
- works with any framework
- flexible
- safe (e.g. will never crash your server)
Installation
$ npm install middleware-json-parseUsage
const parseJson = require('middleware-json-parse')
const middleware = require('http-middleware')
const http = require('http')
http.createServer((req, res) => {
const mw = [ parseJson(req, 'body') ]
middleware(req, res, mw, (err) => {
res.statusCode = err ? 500 : 200
console.log('body', req.body)
res.end()
})
}).listen()API
parser = parseJson(ctx, propName, errFn?)
Create safe json parsing middleware. Requires a context object on which to
set a propName containing the body value (in express: req, 'body').
Takes an optional function as the third argument to format errors that are
passed to next. Errors are by default formatted as new Error({ message:
'Invalid JSON' }).
parser(req, res, next?)
Safely parse JSON data from req, mount it on the context as propName,
and call next when done. Only parses content if the
Content-Type=application/json HTTP header is set.