Minimal Koa.JS example with Router & Body parser
This is the minimal Koa.JS application which I use as a template for new NodeJS webserver applications.
#!/usr/bin/env node
const router = require('koa-router')();
const koaBody = require('koa-body');
const Koa = require('koa');
const app = new Koa();
app.use(koaBody());
router.get('/', async ctx => {
ctx.body = "Hello world";
});
app.use(router.routes());
if (!module.parent) app.listen(3000);
Install the requirements using
npm i --save koa koa-router koa-body
and run using
node index.js
assuming you have saved our code from above in index.js
.
Now (with the node index.js
command still running) go to http://localhost:3000 . You should see Hello world
there. Now it’s your turn to continue on your endeavour to develop the world’s greatest webservers :-)