Skip to content

Latest commit

 

History

History
229 lines (164 loc) · 4.45 KB

learn koa2--tools.md

File metadata and controls

229 lines (164 loc) · 4.45 KB

Table of Contents generated with DocToc

learn koa2--tools

Tools

$ npm install koa-views@next --save
// usage
import views from 'koa-views';

views(templateDirPath, option);

// 在templates文件夹下,以`.html`结尾的文件都会安装nunjucks模板进行处理
views(__dirname + '/templates', { map: {html: 'nunjucks' }});


// example
import Koa from 'koa';
import views from 'koa-views';

const app = new Koa();
app.use(views(__dirname + '/templates', {
  map: {
    html: 'nunjucks'
  }
}));

app.listen(7000);
export default app;
$ npm install koa-logger --save
// usage
import Koa from 'koa';
import convert from 'koa-convert';
import logger from 'koa-logger';

const app = new Koa();
app.use(convert(logger()));

app.listen(7000);
export default app;

Koa路由系统

koa-router usage

# for Koa2.X
$ npm install koa-router@next --save

解析request请求中的body成为Object

# for Koa2.X
$ npm install koa-bodyparser@next --save
// usage
import Koa from 'koa';
import bodyParser from 'koa-bodyparser';

const app = new Koa();
app.use(bodyParser());

app.listen(7000);
export default app;

pretty-printed JSON response middleware

$ npm install koa-json --save
import Koa from 'koa';
import convert from 'koa-convert';
import json from 'koa-json';

const app = new Koa();
app.use(convert(json()));

app.listen(7000);
export default app;

更优化的错误消息提示

$ npm install koa-onerror --save
// usage
import Koa from 'koa';
import onerror from 'koa-onerror';

const app = new Koa();
onerror(app);

app.listen(7000);
export default app;

我们刻意的创建一个错误:

router.get('/', async (ctx, next) => {
    await ctx.render('home/indexx', {
        title: 'home page',
        content: 'this is home page'
    });
});

因为并不存在templates/home/indexx.html,所以URL为/时页面在正常情况下报错如下:

without koa-onerror

而使用了koa-onerror之后则:

with koa-onerror

跨域请求的认证,基本必装

$ npm install --save koa-csrf@3.x
// app.js
import csrf from 'koa-csrf';
// ...
app.use(convert(new csrf()));

Templates

$ npm install nunjucks --save
// usage
// app/app.js
import nunjucks from 'nunjucks';
import Koa from 'koa';
import views from 'koa-views';

// 配置nunjucks模板文件所在的路径,否则模板继承时无法使用相对路径
nunjucks.configure(__dirname + '/templates', { autoescape: true });

const app = new Koa();
//views with nunjucks
app.use(views(__dirname + '/templates', {
  map: {
    html: 'nunjucks'
  }
}));

app.listen(7000);
export default app;
$ npm install pug --save

Move to Koa2.X

因为Koa1.X和Koa2.X相比,中间件的方法有较大改变,所以如果把旧的中间件插件,例如koa-logger这样的,用在Koa2项目里时,就会在控制台输出不兼容警告。为此,我们需要一个koa-convert来把旧版本的中间件包裹起来做兼容。

$ npm install koa-convert --save
// usage
import Koa from 'koa';
import logger from 'koa-logger';
import convert from 'koa-convert';

const app = new Koa();
app.use(convert(logger()));

app.listen(7000);
export default app;