@ukab/jbody
v0.2.0
Published
Ukab Ecosystem json body parser
Downloads
3
Maintainers
Readme
Json Body Parser
The library is compitable with both ESM and CommonJS. You can use this package with any framework or even with NodeJS native http module.
Usage
with native http module
const { createServer } = require('http');
const jbody = require('@ukab/jbody');
// // with config
// const jsonParser = jbody({
// exclude: ['/contact'] // optional
// excludeRegex: [new RegExp('/users/.*')] // optional
// sizeLimitInBytes: 1024 // optional
// });
// without config
const jsonParser = jbody();
createServer(async (req, res) => {
const url = new URL(req.url);
const ctx = { req, res, url: url.pathname };
await jsonParser(ctx);
res.end(JSON.stringify({
data: ctx.body,
}));
}).listen(3000);
with koa
app.use(async (ctx, next) => {
await jsonParser(ctx);
await next();
});
with express
app.use((req, res, next) => {
const ctx = { req, res, url: req.url };
jsonParser(ctx)
.then(() => {
next();
}).catch(next);
});