Hello Koa
const Koa = require('koa');
const app = new Koa();
// response
app.use(ctx => {
ctx.body = 'Hello Koa';
});
app.listen(3000);
Getting started
- Kick-Off-Koa - An intro to Koa via a set of self-guided workshops.
- Guide - Go straight to the docs.
Middleware
Koa is a middleware framework that can take two different kinds of functions as middleware:
- async function
- common function
Here is an example of logger middleware with each of the different functions:
async functions (node v7.6+)
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
Common function
// Middleware normally takes two parameters (ctx, next), ctx is the context for one request,
// next is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion.
app.use((ctx, next) => {
const start = Date.now();
return next().then(() => {
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
});
Koa Application
The object created when executing new Koa()
is known as the Koa application object.
The application object is Koa’s interface with node’s http server and handles the registration of middleware, dispatching to the middleware from http, default error handling, as well as configuration of the context, request and response objects.
Learn more about the application object in the Application API Reference.
Troubleshooting
Check the Troubleshooting Guide or Debugging Koa in the general Koa guide.
Running tests
$ npm test
Reporting vulnerabilities
To report a security vulnerability, please do not open an issue, as this notifies attackers of the vulnerability. Instead, please email dead_horse, jonathanong, and niftylettuce to disclose.
Authors
See AUTHORS.
Community
- KoaJS Slack Group
- Badgeboard and list of official modules
- Examples
- Middleware list
- Wiki
- Reddit Community
- Mailing list
- 中文文档 v1.x
- 中文文档 v2.x
- [#koajs] on freenode
Job Board
Looking for a career upgrade?
Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site.