middleware-json-parse

1.0.1 • Public • Published

middleware-json-parse stability

npm version build status test coverage downloads js-standard-style

JSON parsing middleware.

Features:

  • fast
  • works with any framework
  • flexible
  • safe (e.g. will never crash your server)

Installation

$ npm install middleware-json-parse

Usage

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.

License

MIT

Package Sidebar

Install

npm i middleware-json-parse

Weekly Downloads

1

Version

1.0.1

License

MIT

Last publish

Collaborators

  • tabdigital