nodejs koa framework overview

来源:互联网 发布:国内java大牛 编辑:程序博客网 时间:2024/04/17 05:56

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-timeapp.use(async function (ctx, next) {  const start = new Date();  await next();  const ms = new Date() - start;  ctx.set('X-Response-Time', `${ms}ms`);});// loggerapp.use(async function (ctx, next) {  const start = new Date();  await next();  const ms = new Date() - start;  console.log(`${ctx.method} ${ctx.url} - ${ms}`);});// responseapp.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..
1 0
原创粉丝点击