koa-better-response-handler
v3.1.0
Published
Express.js response handler interface for Koa.js (identical).
Downloads
26
Maintainers
Readme
koa-better-response-handler
Express.js response handler interface for Koa.js (identical).
- 🦄 Inspired from Express.js.
- 🔥 Amiable and lightweight handler.
- 💅🏻 Express-style handler (
.send()
,.json()
,.render()
,.statusCode()
etc.) - 🎈 Support for
.render()
methods through koa-views middelware. - 📍 Support for
.jsonp()
methods through koa-safe-jsonp middelware. - ⚖️ Tiny Bundle.
Installation
# koa-is-json: need when you use `.json()` to check passed data is json.
# npm
$ npm i koa-better-response-handler koa-is-json
# yarn
$ yarn add koa-better-response-handler koa-is-json
Usage
This is a practical example of how to use.
const Koa = require('koa');
const responseHandler = require('koa-better-response-handler');
const app = new Koa();
app.use(responseHandler());
// ==> ctx.statusCode(200).send('Hello World')
// ==> ctx.statusCode(200).json({ msg: 'Hello World' })
// ==> ctx.statusCode(200).sendStatus() // OK
OPTIONS
By default koa-better-response-handler
use koa-is-json to validate
the passed data but you can ignore the installation of koa-is-json
and use your custom json checker function by pass and object like this:
app.use(
responseHandler({
isJSON: (data) => {
/* custom json checker */
}
})
);
Note
We don't support render
and jsonp
methods purely by this module
we expect that use some others packages like koa-views
and koa-safe-jsonp
.
.render
Make sure to use koa-views middelware first.
const Koa = require('koa');
const views = require('koa-views'); // support render method.
const responseHandler = require('koa-better-response-handler');
const app = new Koa();
app
.use(views()) // --> ctx.render().
.use(responseHandler());
More information about koa-views
.jsonp
Make sure to use koa-safe-jsonp middelware first.
const Koa = require('koa');
const jsonp = require('koa-safe-jsonp'); // support jsonp method.
const responseHandler = require('koa-better-response-handler');
const app = new Koa();
jsonp(app); // --> ctx.jsonp().
app.use(responseHandler());
More information about koa-safe-jsonp