Beispielcode: Koa.JS mit Router & Body-Parser

This post is also available in: English (Englisch)

Dieser Beispielcode stellt die einfachstmögliche Koa.JS-Applikation dar, die ich als Template für verschiedene Webserver-Projekte verwende.

#!/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 = "Hallo Welt!";
});

app.use(router.routes());

if (!module.parent) app.listen(3000);

Installiere die Abhängigkeiten mit

npm i --save koa koa-router koa-body

und führe den Code so aus, nachdem du den obenstehenden Code als index.js abgespeichert hast:

node index.js

Während node index.js noch läuft, öffne http://localhost:3000 . Du solltest dort Hallo Welt! sehen. Jetzt bist du bereit, das Beispiel zu deiner eigenen Webapplikation auszubauen.