koa as nodejs server framework more simple than express , you should learn es6 ,javascript rather than know koa firstly.
i wonder why that koa chinese document is different from english , may be chinse document is too older .
chinse document : http://koa.rednode.cn/
english document : http://koajs.com/
if you accord to chinese docuemnt will get a lot of error , perhaps chinese translate is long long ago …
First step(install koa as official):
$ nvm install 7
$ npm i koa
// to run your server js : node my-koa-app.js
Second step run server:
const Koa = require('koa');
const app = new Koa();
// ctx is context obj in new version
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
run above script you'll get the response :
ps: if you want some convenient way refer to koa generate http://www.jianshu.com/p/6b816c609669
get nvm : https://github.com/creationix/nvm/blob/master/README.markdown
koa have resolved the problem of node call back you can use es6 async, await function or generator .
const Koa = require('koa');
const app = new Koa();
// x-response-time
app.use(async function (ctx, next) {
const start = new Date();
await next();
const ms = new Date() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// logger
app.use(async function (ctx, next) {
const start = new Date();
await next();
const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});
// response
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
Result:
as the result show, get the GET / -- 5 first then == , that is , when the code run await will go next middleware until last moddleware , reverse execute the code , form logger to response..