Research
Security News
Malicious npm Package Targets Solana Developers and Hijacks Funds
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
A Koa body parser middleware. Supports multipart, urlencoded and JSON request bodies.
koa-body is a middleware for Koa that parses incoming request bodies in various formats, including JSON, URL-encoded, and multipart forms. It simplifies handling file uploads and form submissions in Koa applications.
JSON Body Parsing
This feature allows you to parse JSON bodies from incoming requests. The middleware automatically parses the JSON and makes it available in `ctx.request.body`.
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();
app.use(koaBody());
app.use(async ctx => {
if (ctx.method === 'POST') {
ctx.body = `Received JSON data: ${JSON.stringify(ctx.request.body)}`;
} else {
ctx.body = 'Send a POST request with JSON data';
}
});
app.listen(3000);
URL-encoded Body Parsing
This feature allows you to parse URL-encoded bodies from incoming requests. The middleware automatically parses the URL-encoded data and makes it available in `ctx.request.body`.
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();
app.use(koaBody({ urlencoded: true }));
app.use(async ctx => {
if (ctx.method === 'POST') {
ctx.body = `Received URL-encoded data: ${JSON.stringify(ctx.request.body)}`;
} else {
ctx.body = 'Send a POST request with URL-encoded data';
}
});
app.listen(3000);
Multipart Form Parsing
This feature allows you to parse multipart form data, which is commonly used for file uploads. The middleware automatically parses the multipart data and makes it available in `ctx.request.files`.
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();
app.use(koaBody({ multipart: true }));
app.use(async ctx => {
if (ctx.method === 'POST') {
const files = ctx.request.files;
ctx.body = `Received files: ${JSON.stringify(files)}`;
} else {
ctx.body = 'Send a POST request with multipart form data';
}
});
app.listen(3000);
koa-bodyparser is a middleware for Koa that parses JSON and URL-encoded request bodies. It is simpler and more lightweight compared to koa-body, but it does not support multipart form data parsing.
koa-multer is a middleware for handling multipart/form-data, which is primarily used for uploading files. It is similar to koa-body in terms of file upload capabilities but does not handle JSON or URL-encoded bodies.
koa-better-body is a more feature-rich alternative to koa-body, supporting JSON, URL-encoded, and multipart form data parsing. It also offers additional features like custom body parsers and file renaming.
A full-featured
koa
body parser middleware. Supportmultipart
,urlencoded
andjson
request bodies. Provides same functionality as Express's bodyParser -multer
. And all that is wrapped only aroundco-body
andformidable
.
Install with npm
$ npm install koa-body
$ npm install koa-body@3
To address a potential security issue:
files
property has been moved to ctx.request.files
. In prior versions, files
was a property of ctx.request.body
.fields
property is flatten (merged) into ctx.request.body
. In prior versions, fields
was a property of ctx.request.body
.If you do not use multipart uploads, no changes to your code need to be made.
Versions 1 and 2 of koa-body
are deprecated and replaced with versions 3 and 4, respectively.
npm install koa
npm install koa-body
nvm install v8.11.2 # Note - Koa requires node v7.6.0+ for async/await support
index.js:
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();
app.use(koaBody());
app.use(ctx => {
ctx.body = `Request Body: ${JSON.stringify(ctx.request.body)}`;
});
app.listen(3000);
$ node index.js
$ curl -i http://localhost:3000/users -d "name=test"
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 29
Date: Wed, 03 May 2017 02:09:44 GMT
Connection: keep-alive
Request Body: {"name":"test"}%
For a more comprehensive example, see examples/multipart.js
It's generally better to only parse the body as needed, if using a router that supports middleware composition, we can inject it only for certain routes.
const Koa = require('koa');
const app = new Koa();
const router = require('koa-router')();
const koaBody = require('koa-body');
router.post('/users', koaBody(),
(ctx) => {
console.log(ctx.request.body);
// => POST body
ctx.body = JSON.stringify(ctx.request.body);
}
);
app.use(router.routes());
app.listen(3000);
console.log('curl -i http://localhost:3000/users -d "name=test"');
Options available for
koa-body
. Four custom options, and others are fromraw-body
andformidable
.
patchNode
{Boolean} Patch request body to Node's ctx.req
, default false
patchKoa
{Boolean} Patch request body to Koa's ctx.request
, default true
jsonLimit
{String|Integer} The byte (if integer) limit of the JSON body, default 1mb
formLimit
{String|Integer} The byte (if integer) limit of the form body, default 56kb
textLimit
{String|Integer} The byte (if integer) limit of the text body, default 56kb
encoding
{String} Sets encoding for incoming form fields, default utf-8
multipart
{Boolean} Parse multipart bodies, default false
urlencoded
{Boolean} Parse urlencoded bodies, default true
text
{Boolean} Parse text bodies, default true
json
{Boolean} Parse json bodies, default true
jsonStrict
{Boolean} Toggles co-body strict mode; if set to true - only parses arrays or objects, default true
includeUnparsed
{Boolean} Toggles co-body returnRawBody option; if set to true, for form encodedand and JSON requests the raw, unparsed requesty body will be attached to ctx.reqeust.body
using a Symbol
, default false
formidable
{Object} Options to pass to the formidable multipart parseronError
{Function} Custom error handle, if throw an error, you can customize the response - onError(error, context), default will throwstrict
{Boolean} If enabled, don't parse GET, HEAD, DELETE requests, default true
see http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-19#section-6.3
Some applications require crytopgraphic verification of request bodies, for example webhooks from slack or stripe. The unparsed body can be accessed if includeUnparsed
is true
in koa-body's options. When enabled, import the symbol for accessing the request body from unparsed = require('koa-body/unparsed.js')
, or define your own accessor using unparsed = Symbol.for('unparsedBody')
. Then the unparsed body is available using ctx.request.body[unparsed]
.
See node-formidable for a full list of options
maxFields
{Integer} Limits the number of fields that the querystring parser will decode, default 1000
maxFieldsSize
{Integer} Limits the amount of memory all fields together (except files) can allocate in bytes. If this value is exceeded, an 'error' event is emitted, default 2mb (2 * 1024 * 1024)
uploadDir
{String} Sets the directory for placing file uploads in, default os.tmpDir()
keepExtensions
{Boolean} Files written to uploadDir
will include the extensions of the original files, default false
hash
{String} If you want checksums calculated for incoming files, set this to either 'sha1'
or 'md5'
, default false
multiples
{Boolean} Multiple file uploads or no, default true
onFileBegin
{Function} Special callback on file begin. The function is executed directly by formidable. It can be used to rename files before saving them to disk. See the docsNote: You can patch request body to Node or Koa in same time if you want.
$ npm test
The MIT License, 2014 Charlike Mike Reagent (@tunnckoCore) and Daryl Lau (@daryllau)
4.0.0 - 4.0.8 - Summary of Changes
includeUnparsed
option to get raw bodyTo address a potential security vulnerability:
files
property has been moved to ctx.request.files
. In prior versions, files
was a property of ctx.request.body
.fields
property is flatten (merged) into ctx.request.body
. In prior versions, fields
was a property of ctx.request.body
.If you do not use multipart uploads, no changes to your code need to be made.
Versions 1 and 2 of koa-body
are deprecated and replaced with versions 3 and 4, respectively.
FAQs
A Koa body parser middleware. Supports multipart, urlencoded and JSON request bodies.
The npm package koa-body receives a total of 277,459 weekly downloads. As such, koa-body popularity was classified as popular.
We found that koa-body demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.