koa介绍 #

koa.js 是下一代的node.js框架

环境准备 #

安装 #

npm init -y
npm install koa

创建应用 #

const Koa = require('koa')
const app = new Koa()

app.use(ctx => {
  ctx.body = 'hello koa2'
})

app.listen(3000)
console.log('[demo] start-quick is starting at port 3000')

启动服务 #

node server.js

访问 http:localhost:3000

async/await #

中间件 #

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);

原生路由 #

const Koa = require('koa');
const fs = require('fs');
const app = new Koa();
async function route(url) {
  let filename = `./views/${url}.html`;
  return new Promise(function (resolve, reject) {
    fs.readFile(filename, 'utf8', function (err, data) {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    })
  });
}
app.use(async ctx => {
  let html = await route(ctx.request.url);
  ctx.body = html;
});
app.listen(3000);

路由中间件 #

let Koa = require('koa');
let app = new Koa();
let Router = require('koa-router');
let router = new Router();
router.get('/', ctx => {
  ctx.body = 'home';
});

router.get('/user', ctx => {
  ctx.body = 'user';
});

router.get('/404', ctx => {
  ctx.body = '404';
});

app.use(router.routes(),router.allowedMethods());

app.listen(3000);

GET请求数据获取 #

在koa中,获取GET请求数据源头是koa中request对象中的query方法或querystring方法,query返回是格式化好的参数对象,querystring返回的是请求字符串

const Koa = require('koa');
const app = new Koa();
app.use(ctx => {
  let url = ctx.url;
  let query = ctx.query;
  let querystring = ctx.querystring;
  ctx.body = {
    url,
    query,
    querystring
  }
});
app.listen(3000);

POST请求参数获取 #

对于POST请求的处理,koa2没有封装获取参数的方法,需要通过解析上下文context中的原生node.js请求对象req,将POST表单数据解析成query string(例如:a=1&b=2&c=3),再将query string 解析成JSON格式(例如:{"a":"1", "b":"2", "c":"3"})

const Koa = require('koa');
let querystring = require('querystring');
const app = new Koa();
async function parseBody(req){
  return new Promise(function(resolve,reject){
    let buffers = [];
    req.on('data',function(data){
      buffers.push(data);
    });
    req.on('end',function(){
      let result = Buffer.concat(buffers).toString();
      resolve(querystring.parse(result));
    });
    req.on('err',function(err){
      reject(err);
    });
  });
}
app.use(async ctx => {
  if (ctx.request.url == '/' && ctx.request.method == 'GET') {
    ctx.body = (
      `
        <form method="post"><input type="text" name="username"/><input type="submit"/></form>
      `
    )
  } else if (ctx.request.url == '/' && ctx.request.method == 'POST') {
    let html = await parseBody(ctx.req);
    ctx.body = html;
  }else{
    ctx.body = '404';
  }
});
app.listen(3000);

koa-bodyparser中间件 #

对于POST请求的处理,koa-bodyparser中间件可以把koa2上下文的formData数据解析到ctx.request.body中 安装koa2版本的koa-bodyparser@3中间件

npm install --save koa-bodyparser@3

koa-static中间件使用 #

const Koa = require('koa');
const path = require('path');
const static = require('koa-static');
const app = new Koa();
app.use(static(
  path.resolve('./static')
));
app.use(ctx => {
  ctx.body = '404';
});
app.listen(3000);

cookie #

koa提供了从上下文直接读取、写入cookie的方法

const Koa = require('koa');
const path = require('path');
const app = new Koa();

app.use(ctx => {
  let visit = ctx.cookies.get('visit');
  if(visit){
    visit = parseInt(visit)+1;
  }else {
    visit = 1;
  }
  ctx.cookies.set('visit',visit);
  ctx.body = `这是你的第${visit}次访问`;
});
app.listen(3000);

session #

const Koa = require('koa');
const app = new Koa();
const session = require('koa-session');
app.keys = ['some secret hurr'];
let options = {

}
app.use(session(options,app));
app.use(ctx=>{
  let visit = ctx.session.visit;
  if(visit){
    visit = visit + 1;
  }else{
    visit = 1;
  }
  ctx.session.visit = visit;
  ctx.body = `${visit}`;
});
app.listen(3000);

模板渲染 #

const Koa = require('koa');
const views = require('koa-views');
const path = require('path');
const app = new Koa();
app.use(views(path.join(__dirname, './views'), {extension: 'ejs'}));
app.use(async ctx=>{
  let title = 'hello koa2';
  await ctx.render('index',{title:title});
});
app.listen(3000);

最佳实践 #

https://www.npmjs.com/package/generator-k

koa2学习笔记 zhufeng-koa2