ko2 常用中间件

微信扫一扫,分享到朋友圈

ko2 常用中间件

ko2 常用中间件

**目录**

  • 一、koa-bodyparser
  • 二、koa-router
  • 三、koa-views + ejs
  • 四、koa-static
  • 五、koa-session
  • 六、koa-jwt
  • 七、koa-helmet
  • 八、koa-compress
  • 九、koa-logger
  • 十、koa-convert
  • 十一、koa-compose
  • 十二、koa-http-request
  • 十三、koa-conditional-get
  • 十四、koa-csrf
  • 十五、koa-ejs
  • 十六、koa-etag
  • 十七、koa-favicon
  • 十八、koa-generic-session
  • 十九、koa-onerror
  • 二十、koa-redis
  • 二十一、koa-resource-router
  • 二十二、koa-rewrite
  • 二十三、koa-rt
  • 二十四、koa-safe-jsonp
  • 二十五、koa-static-cache

一、koa-bodyparser[1]

1、功能:解析请求体

2、官网

3、代码实现

const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
app.use(async(ctx)=>{
if(ctx.url === '/' && ctx.method === 'GET'){
//显示表单页面
let html=`
<h1>Koa2 request POST</h1>
<form method="POST" action="/">
<p>userName</p>
<input name="userName" /><br/>
<p>age</p>
<input name="age" /><br/>
<button type="submit">submit</button>
</form>
`;
ctx.body=html;
}else if(ctx.url === '/' && ctx.method === 'POST'){
let postData = ctx.request.body;
ctx.body = postData;
}else{
ctx.body = '<h1>404!</h1>';
}
});
app.listen(3000, () => {
console.log('[demo] server is starting at port 3000');
});
复制代码

二、koa-router[2]

1、功能:路由

2、官网

3、基础格式

const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
//实现 '/'、'/koa'两个路由层级
router
.get('/',(ctx,next)=>{
ctx.body="Index page";
})
.get('/koa',(ctx,next)=>{
ctx.body="Koa page";
});
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000,()=>{
console.log('starting at port 3000');
});
复制代码

4、路由层级

(1)全局层级

//所有路由必须加上一个tony父层级,才能被访问
const router = new Router({
prefix: '/tony'
})
复制代码

(2)局部层级

const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
//实现'/home'、'/page'两个子路由层级,以及各自的两个孙子路由层级
//子路由
let home = new Router();
home
.get('/',async(ctx)=>{
ctx.body="Home";
})
.get('/one',async(ctx)=>{
ctx.body="Home one";
})
.get('/two',async(ctx)=>{
ctx.body ='Home two';
})
let page = new Router();
page
.get('/',async(ctx)=>{
ctx.body="Page";
})
.get('/one',async(ctx)=>{
ctx.body="Page one";
})
.get('/two',async(ctx)=>{
ctx.body ='Page two';
})
//总路由,装载子路由
let router = new Router();
router.use('/home',home.routes(),home.allowedMethods());
router.use('/page',page.routes(),page.allowedMethods());
//加载路由中间件
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000,()=>{
console.log('[demo] server is starting at port 3000');
});
复制代码

三、koa-views + ejs[3]

1、功能:视图模板渲染

2、koa-views官网 && ejs官网

3、在根目录下,新建views文件夹,并添加index.ejs

<!-- index.ejs -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><%=title%></title>
</head>
<body>
<h1><%=title%></h1>
</body>
</html>
复制代码

4、代码实现

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'
//渲染index.ejs,并传入title变量
await ctx.render('index', {
title
})
})
app.listen(3000,()=>{
console.log('[demo] server is starting at port 3000');
})
复制代码

四、koa-static[4]

1、功能:处理静态资源

2、官网

3、代码实现

const Koa = require('koa')
const path = require('path')
const static = require('koa-static')
const app = new Koa()
const staticPath = './static'
//即可直接通过'./static',访问到静态资源
app.use(static(
path.join(__dirname, staticPath)
))
app.use( async ( ctx ) => {
ctx.body = 'hello world'
})
app.listen(3000, () => {
console.log('[demo] static-use-middleware is starting at port 3000')
})
复制代码

五、koa-session

1、功能:session验证

2、官网

3、代码实现

const session = require('koa-session');
const Koa = require('koa');
const app = new Koa();
app.keys = ['some secret hurr'];
const CONFIG = {
key: 'koa.sess',
/** (string) cookie key (default is koa.sess) */
/** (number || 'session') maxAge in ms (default is 1 days) */
/** 'session' will result in a cookie that expires when session/browser is closed */
/** Warning: If a session cookie is stolen, this cookie will never expire */
maxAge: 86400000,  autoCommit: true, /** (boolean) automatically commit headers (default true) */
overwrite: true, /** (boolean) can overwrite or not (default true) */
httpOnly: true, /** (boolean) httpOnly or not (default true) */
signed: true, /** (boolean) signed or not (default true) */
rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
secure: true, /** (boolean) secure cookie*/
sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */
};
app.use(session(CONFIG, app));// or if you prefer all default config, just use => app.use(session(app)); app.use(ctx => {  // ignore favicon  if (ctx.path === '/favicon.ico') return;
let n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = n + ' views';});
app.listen(3000);console.log('listening on port 3000');
复制代码

六、koa-jwt

1、功能:token验证

2、官网

var Koa = require('koa');
var jwt = require('koa-jwt');
var app = new Koa(); // Middleware below this line is only reached if JWT token is valid
// unless the URL starts with '/public'
app.use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\/public/] })); // Unprotected middleware
app.use(function(ctx, next){
if (ctx.url.match(/^\/public/)) {
ctx.body = 'unprotected\n';
} else {
return next();
}
}); // Protected middleware
app.use(function(ctx){
if (ctx.url.match(/^\/api/)) {
ctx.body = 'protected\n';
}
});
app.listen(3000);
复制代码

七、koa-helmet

1、功能:网络安全

2、官网

"use strict";
const Koa = require("koa");
const helmet = require("koa-helmet");
const app = new Koa();
app.use(helmet());
app.use((ctx) => {
ctx.body = "Hello World"
});
app.listen(4000);
复制代码

八、koa-compress

1、功能:压缩响应体

2、官网

const compress = require('koa-compress');
const Koa = require('koa')
const app = new Koa()
app.use(compress({
filter (content_type) {
return /text/i.test(content_type)
},
threshold: 2048,
gzip: {
flush: require('zlib').constants.Z_SYNC_FLUSH
},
deflate: {
flush: require('zlib').constants.Z_SYNC_FLUSH,
},
br: false // disable brotli}))
复制代码

九、koa-logger

1、功能:输出请求日志

2、官网

const logger = require('koa-logger')
const Koa = require('koa')
const app = new Koa()
app.use(logger((str, args) => {
// redirect koa logger to other output pipe
// default is process.stdout(by console.log function)
}))
复制代码

十、koa-convert

1、功能:旧中间件(基于generate)、新中间件(基于promise)之间的互相转换

2、官网

3、代码实现

const Koa = require('koa') // koa v2.x
const convert = require('koa-convert')
const app = new Koa()
app.use(modernMiddleware)
app.use(convert(legacyMiddleware))
app.use(convert.compose(legacyMiddleware, modernMiddleware))
function * legacyMiddleware (next) {  // before  yield next  // after}
function modernMiddleware (ctx, next) {  // before  return next().then(() => {    // after  })}
复制代码

十一、koa-compose

1、功能:合并中间件

2、官网

3、代码实现

十二、koa-http-request

1、功能:请求

2、官网

const koa = require('koa');
const koaRequest = require('koa-http-request');
const app = new koa();
app.use(koaRequest({
json: true, //automatically parsing of JSON response
timeout: 3000,    //3s timeout
host: 'https://api.github.com'
}));
app.use(async (ctx, next) => {    l
et repo = await ctx.get('/repos/junyiz/koa-http-request', null, {
'User-Agent': 'koa-http-request'
});
ctx.body = 'repos id: ' + repo.id + '\nrepos name: ' + repo.full_name;});
app.listen(process.env.PORT || 8090);
复制代码

十三、koa-conditional-get

1、功能:有条件地获得对koa的支持。

2、官网

3、代码实现

const conditional = require('koa-conditional-get');
const etag = require('koa-etag');
const Koa = require('koa');
const app = new Koa(); // use it upstream from etag so// that they are present
app.use(conditional()); // add etags
app.use(etag()); // respond
app.use(async function(ctx, next){
await next();
ctx.body = {
name: 'tobi',
species: 'ferret',
age: 2
};
})
app.listen(  3000,  console.log('listening on port 3000'))
复制代码

十四、koa-csrf

1、功能:

2、官网

3、代码实现

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const session = require('koa-generic-session');
const convert = require('koa-convert');
const CSRF = require('koa-csrf');
const app = new Koa(); // set the session keys
app.keys = [ 'a', 'b' ]; // add session support
app.use(convert(session())); // add body parsing
app.use(bodyParser()); // add the CSRF middleware
app.use(new CSRF({
invalidTokenMessage: 'Invalid CSRF token',
invalidTokenStatusCode: 403,
excludedMethods: [ 'GET', 'HEAD', 'OPTIONS' ],
disableQuery: false
})); // your middleware here (e.g. parse a form submit)
app.use((ctx, next) => {
if (![ 'GET', 'POST' ].includes(ctx.method))    return next();
if (ctx.method === 'GET') {
ctx.body = ctx.csrf;
return;
}
ctx.body = 'OK';
});
app.listen();
复制代码

十五、koa-ejs

1、功能:koa模板

2、官网

3、代码实现

const Koa = require('koa');
const render = require('koa-ejs');
const path = require('path');
const app = new Koa();
render(app, {
root: path.join(__dirname, 'view'),
layout: 'template',  viewExt: 'html',
cache: false,
debug: true
});
app.use(async function (ctx) {
await ctx.render('user');
});
app.listen(7001);
复制代码

十六、koa-etag

1、功能:Etag支持使用Etag的Koa响应。

2、官网

3、代码实现

const conditional = require('koa-conditional-get');
const etag = require('koa-etag');
const Koa = require('koa');
const app = new Koa(); // etag works together with conditional-get
app.use(conditional());
app.use(etag());
app.use(function (ctx) {
ctx.body = 'Hello World';
});
app.listen(3000);
console.log('listening on port 3000');
复制代码

十七、koa-favicon

1、功能:favicon

2、官网

3、代码实现

const Koa = require('koa');
const favicon = require('koa-favicon');
const app = new Koa();
app.use(favicon(__dirname + '/public/favicon.ico'));
复制代码

十八、koa-generic-session

1、功能:session1

2、官网

3、代码实现

var session = require('koa-generic-session');
var redisStore = require('koa-redis');
var koa = require('koa');
var app = new koa(); // for koa v1 use `var app = koa();`
app.keys = ['keys', 'keykeys'];
app.use(session({  store: redisStore()}));
app.use(function *() {
switch (this.path) {
case '/get':
get.call(this);
break;
case '/remove':
remove.call(this);
break;
case '/regenerate':
yield regenerate.call(this);
break;
}});
function get() {
var session = this.session;
session.count = session.count || 0;
session.count++;
this.body = session.count;
}
function remove() {
this.session = null;
this.body = 0;
}
function *regenerate() {
get.call(this);
yield this.regenerateSession();  g
et.call(this);
}
app.listen(8080);
复制代码

十九、koa-onerror

1、功能:异常中间件

2、官网

3、代码实现

const fs = require('fs');
const koa = require('koa');
const onerror = require('koa-onerror');
const app = new koa();
onerror(app);
app.use(ctx => {  // foo();
ctx.body = fs.createReadStream('not exist');
});
复制代码

二十、koa-redis

1、功能:redisStore

2、官网

3、代码实现

const session = require('koa-generic-session');
const redisStore = require('koa-redis');
const koa = require('koa');
const app = koa();
app.keys = ['keys', 'keykeys'];
app.use(session({  store: redisStore({    // Options specified here  })}));
app.use(function *() {
switch (this.path) {
case '/get':    get.call(this);    break;
case '/remove':    remove.call(this);    break;
case '/regenerate':    yield regenerate.call(this);    break;
}});
function get() {
const session = this.session;
session.count = session.count || 0;
session.count++;
this.body = session.count;
}
function remove() {
this.session = null;
this.body = 0;
}
function *regenerate() {
get.call(this);
yield this.regenerateSession();
get.call(this);
}
app.listen(8080);
复制代码

二十一、koa-resource-router

1、功能:资源路由

2、官网

3、代码实现

var Resource = require('koa-resource-router');
var app = require('koa')();
var users = new Resource('users', {  // GET /users
index: function *(next) {  },  // GET /users/new
new: function *(next) {  },  // POST /users
create: function *(next) {  },  // GET /users/:id
show: function *(next) {  },  // GET /users/:id/edit
edit: function *(next) {  },  // PUT /users/:id
update: function *(next) {  },  // DELETE /users/:id
destroy: function *(next) {  }
});
app.use(users.middleware());
复制代码

二十二、koa-rewrite

1、功能:重写

2、官网

3、代码实现

app.use(rewrite(/^\/i(\w+)/, '/items/$1'));
复制代码

二十三、koa-rt

1、功能:机制

2、官网

3、代码实现

var koa = require('koa');
var rt = require('koa-rt');
var app = koa();
app.use(rt());
app.use(function *(next){
yield sleep(150);
this.body = 'Hello';
});
function sleep(ms) {
return function(done){
setTimeout(done, ms);
};
}
app.listen(7001);
console.log('listening on port 7001');
复制代码

二十四、koa-safe-jsonp

1、功能:安全的jsonp

2、官网

3、代码实现

const jsonp = require('koa-safe-jsonp');
const Koa = require('Koa');
const app = new Koa();
jsonp(app, {
callback: '_callback', // default is 'callback'
limit: 50, // max callback name string length, default is 512
});
app.use(function (ctx) {
ctx.jsonp = {foo: "bar"};
});
app.listen(1984);
复制代码

二十五、koa-static-cache

1、功能:静态资源缓存

2、官网

3、代码实现

var path = require('path')
var staticCache = require('koa-static-cache')
app.use(staticCache(path.join(__dirname, 'public'), {  maxAge: 365 * 24 * 60 * 60}))
复制代码

微信扫一扫,分享到朋友圈

ko2 常用中间件

c++11 新特性实战 (一):多线程操作

上一篇

SpaceX再赢NASA新合同:将协助研究危险太阳辐射

下一篇

你也可能喜欢

ko2 常用中间件

长按储存图像,分享给朋友