Koa Body Enhancing Middleware Functionality for Node.js Applications

Introduction to Koa-Body

Koa-Body is a fully-featured body parser middleware for Koa, which allows you to handle various types of request bodies such as JSON, URL-encoded data, and multipart forms in your Koa applications.

Installation

npm install koa-body

Basic Usage


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 = `Request Body: ${JSON.stringify(ctx.request.body)}`;
    } else {
        ctx.body = 'Send a POST request to see koa-body in action.';
    }
});

app.listen(3000);
console.log('Server running on http://localhost:3000');

API Examples

JSON Body Parsing


const app = new Koa();

app.use(koaBody());

app.use(async ctx => {
    if (ctx.is('application/json')) {
        ctx.body = {
            status: 'success',
            data: ctx.request.body
        };
    } else {
        ctx.status = 400;
        ctx.body = {
            status: 'fail',
            message: 'Only JSON requests are allowed'
        };
    }
});

app.listen(3000);

URL-encoded Body Parsing


app.use(koaBody({
    urlencoded: true
}));

app.use(async ctx => {
    ctx.body = {
        status: 'success',
        data: ctx.request.body
    };
});

app.listen(3000);

Multipart/Form-Data Parsing


app.use(koaBody({
    multipart: true
}));

app.use(async ctx => {
    if (ctx.method === 'POST') {
        const files = ctx.request.files;
        const body = ctx.request.body;
        
        ctx.body = {
            status: 'success',
            files: files,
            data: body
        };
    } else {
        ctx.body = 'Upload a file to see multipart/form-data in action.';
    }
});

app.listen(3000);

Extensive Body Parsing Options

Text Body Parsing


app.use(koaBody({
    text: true,
    textLimit: '1mb'
}));

app.use(async ctx => {
    if (ctx.is('text/plain')) {
        ctx.body = {
            text: ctx.request.body
        };
    } else {
        ctx.status = 400;
        ctx.body = 'Plain text requests only!';
    }
});

app.listen(3000);

Handling File Uploads


const fs = require('fs');
const path = require('path');

app.use(koaBody({
    multipart: true,
    formidable: {
        uploadDir: path.join(__dirname, 'uploads'),
        keepExtensions: true
    }
}));

app.use(async ctx => {
    if (ctx.method === 'POST') {
        const files = ctx.request.files;
        
        // Process the uploaded file here
        
        ctx.body = {
            status: 'success',
            files: files
        };
    } else {
        ctx.body = 'Upload a file to see handling file uploads in action.';
    }
});

app.listen(3000);

Comprehensive App Example


const Koa = require('koa');
const Router = require('koa-router');
const koaBody = require('koa-body');
const app = new Koa();
const router = new Router();

// Middleware
app.use(koaBody({
    multipart: true,
    urlencoded: true
}));

// Routes
router.get('/', async ctx => {
    ctx.body = 'Welcome to the Koa Body Parser Example!';
});

router.post('/json', async ctx => {
    ctx.body = ctx.request.body;
});

router.post('/urlencoded', async ctx => {
    ctx.body = ctx.request.body;
});

router.post('/upload', async ctx => {
    const files = ctx.request.files;
    const body = ctx.request.body;
    ctx.body = { files, body };
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});

Hash: 6d2b5710bb0a79cc41aed0fb3f957e85e9ff8e3232f7726c58830393443e27e3

Leave a Reply

Your email address will not be published. Required fields are marked *