文章导航

1,koa2使用;

2,写中间件;

3,koa2路由配置angular2;

一。先上代码,一篇,看完koa2中大多基础方法

const Koa=require('koa');
const app=new Koa();
//middleWare:
const Router=require('koa-router');
const mount=require('koa-mount');
const staticCache=require('koa-static-cache');
const session=require('koa-session');
cosnt bodyParser=require('koa-bodyParser');
const send=require('koa-send');
const convert=require('koa-convert');
const co=require('co'); //使用bodyParser和session(following):
app.use(bodyParser());
app.keys=['mykeys'];
const sessionConfig={
key:'myKey', //cookie中的key命名为myKey。可以不定义使用默认值。
}
app.use(convert(session(sessionConfig,app)));
app.use(co.wrap(function* (ctx,next){
//自己定义了一个路由,接受url为 /myTest时,返回信息(following):
if(ctx.path==='myTest'){
//为其配备GET,POST方法(following):
switch(ctx.method){
case 'GET':
ctx.session.views=++ctx.session.views||0;
ctx.body=ctx.session.views;
case 'POST':
ctx.body=JSON.stringify(ctx.bodyParser);
}
}
yield next();
})) //使用路由中间件(following):
const router=new Router();
const childRouter=new Router();
childRouter.get(
'/',
(ctx,next)=>{
ctx.body='Child Content';
return next();
},
(ctx,next)=>{
ctx.body+='Attach Content';
}
)
//可以通过next,连用。也可以仅如下使用(following):
router.get('/', (ctx,next)=>{
ctx.body='hello';
})
//将两个路由拼起来(following):
router.use(
'/child',
childRouter.routes(),
childRouter.allowedMethods()
) app.use(mount( '/routerPath', router.routes() ));
app.use(mount( '/routerPath', router.allowedMethods()));
//(above)又将router,局限在‘routerPath’路径。
app.use(mount(
'/static',
convert(staticCache(
__dirname+'/static',
{age:12000,usePrecompiledGzip:true}
//(above)在static下,托管目录为static的静态文件,设置cache-age=1200;并允许使用预先压缩好的gzip
));
)) //你也可以使用send,来单独发送一个文件(following):
app.use (mount('/jquery.min.js', (ctx,next)=>{
ctx.set( ' Content-Type','text/html');
ctx.set( ' Content-Encoding', ' gzip');
return send(ctx,'./js/jquery.min.js'); //jquery.min.js是gzip文件。
}))
//或者自己写一个简易(不判断content-type)的具备koa-static功能的(following):
const fs=require('fs');
app.use( mount('/myStatic',(ctx,next)=>{
let readStream=fs.createReadStream('./static'+ctx.path);
ctx.body=readStream;
}))
//(above)通过ctx.path获得/myStatic下的相对url。
// 在Http模块下readStream.pipe(res); 而koa中ctx.body会自动处理流。 app.listen(3000);

 

二,自己写一个中间件;

比如我们只想对cookie进行加密和解密使用:

myCookie.js:

const co=require('co');
const crypto=require('crypto');
const encrypt=function(val,key,method='aes192'){
let cipher=crypto.createCipher(method,key);
cipher.update(val,'utf8','hex');
return cipher.final('hex');
}
const decrypt=function(val,key,method='aes192'){
let deCipher=crypto.createDeCipher(method,key);
deCipher.update(val,'hex','utf8');
return cipher.final('utf8');
} module.exports=function(key,method='aes192'){
return co.wrap(function* (ctx,next){
let originalSet=ctx.cookies.set.bind(ctx.cookies);
let originalGet=ctx.cookies.get.bind(ctx.cookies);
//重新定义cookies.set具备加密功能:
ctx.cookies.set=function(...args){
try{
args[1]=encrypt(args[1],key,method);
originalSet(...args);
}catch(e){console.log(e)}
}
//重新定义cookies.get具备解密功能:
ctx.cookies.get=function(...args){
try{
args[1]=decrypt(args[1],key,method);
originalGet(...args);
}catch(e){console.log(e)};
}
//增加一个清除cookie的功能:
ctx.cookies.clear=function(name){
if(!name) return;
let d= new Date();
d.setTime(d.getTime()-1);
ctx.cookies.set(name, ' ' ,{expires:d});
}
yield next(); //最后别忘了yield next;
} )
}

在app.js中使用:

const myCookie=require('./myCookie.js')('mykey');
app.use(myCookie);
app.keys=['mykey2'];
app.use((ctx)=>{
ctx.cookies.set('name', 'Jnew ',{signed:true});
ctx.cookies.clear('preName');
})

与普通ctx.cookies.set相同的用法,但是存入的cookie却是经过加密的。

signed:true时的解释:

    The cookie will still be visible, but it has a signature, so it can detect if the client modified the cookie.

    It works by creating a HMAC of the value (current cookie), and base64 encoded it. When the cookie gets read, it recalculates the signature and makes sure that it matches the signature attached to it.

    If it does not match, then it will give an error.

    If you want to hide the contents of the cookie as well, you should encrypt it instead (or just stores it in the server side session). I'm not sure if there is middleware for that already out there or not.

server side session:

  PS:使用redis内存数据库是一个比较好的解决方法。可是耗性能。就像我不用动态compress,而只是静态托管已压缩好的文件一样。很早前就想过,将MVC这样的构架从服务器中解脱出来,放在前端进行处理,毕竟服务器渲染HTML也是耗性能的。然后自己兴致勃勃地写了一个简单的基于socket的前端模块加载器,然后发现已经有了react 和后来angular2这样的东西。毕竟我只是野路子的医学生,那时又不爱逛社区。闭门造车真是可怕。。。- -!

三,托管Angular2前端路由:

frontEndComponent.js

const fs=require('fs');
const send=require('koa-send'); module.exports=function(path){
return async(ctx,next)=>{
let fileExist=await function(){
return new Promose((resolve,reject)=>{
fs.access(path+ctx.path,err=>{
if(!!err||ctx.path==='/'){
resolve(false);
}else{
resolve(true);
}
})
})
}();
if (fileExist){ // typeof fileExist :boolean ..不是promise
await send(ctx,path+ctx.path);
}else{
await send(ctx,path+'/index.html');
}
}
}

不能直接托管于static下,因为浏览器中输入地址时,前端路由会失效。根据地址判断,服务器中对应的文件是否存在,不存在则返回index.html。该例使用async/await语法。需要babel编译。

 app.js:

var frontEndComponent=require('./frontEndComponent');
var mount=require('koa-mount');
app.use(mount('/example-router',frontEndComponent('./dist')));
app.use((ctx)=>{
ctx.body='empty';
})
app.listen(3000);

  后端将example-router这个地址及其子地址,分配给'/dist'目录下的前端组件来管理。

注意:index.html  中  <base href='/example-router/'>;

  我已经托管到npm,可以直接使用这个包:

  
npm install koa-angular-proxy

koa2使用&&中间件&&angular2的koa托管的更多相关文章

  1. 下篇:express、koa1、koa2的中间件原理

    本作品采用知识共享署名 4.0 国际许可协议进行许可.转载联系作者并保留声明头部与原文链接https://luzeshu.com/blog/express-koa 本博客同步在http://www.c ...

  2. koa中间件机制详解

    转自:https://cnodejs.org/topic/58fd8ec7523b9d0956dad945 koa是由express原班人马打造的一个更小.更富有表现力.更健壮的web框架. 在我眼中 ...

  3. Koa2 和 Express 中间件对比

    koa2 中间件 koa2的中间件是通过 async await 实现的,中间件执行顺序是"洋葱圈"模型. 中间件之间通过next函数联系,当一个中间件调用 next() 后,会将 ...

  4. 全栈项目|小书架|服务器开发-Koa2中间件机制洋葱模型了解一下

    KOA2 是什么? Koa是一个新的 web 框架,由 Express 幕后的原班人马打造, 致力于成为 web 应用和 API 开发领域中的一个更小.更富有表现力.更健壮的基石. 通过利用 asyn ...

  5. Koa框架实践与中间件原理剖析

     最近尝试用了一下Koa,并在此记录一下使用心得. 注意:本文是以读者已经了解Generator和Promise为前提在写的,因为单单Generator和Promise都能够写一篇博文来讲解介绍了,所 ...

  6. 深入探析koa之中间件流程控制篇

    koa被认为是第二代web后端开发框架,相比于前代express而言,其最大的特色无疑就是解决了回调金字塔的问题,让异步的写法更加的简洁.在使用koa的过程中,其实一直比较好奇koa内部的实现机理.最 ...

  7. Koa 框架整理

    学习交流 Koa使用了ES6规范的generator和异步编程是一个更轻量级Web开发的框架,Koa 的先天优势在于 generator.由于是我个人的分享交流,所以Node基础.ES6标准.Web开 ...

  8. koa2教程(一)-快速开始

    来自Koa官网对于Koa的简介: koa 是由 Express 原班人马打造的,致力于成为一个更小.更富有表现力.更健壮的 Web 框架. 使用 koa 编写 web 应用,通过组合不同的 async ...

  9. 基于 Vue + Koa2 + MongoDB + Redis 实现一个完整的登录注册

    项目地址:https://github.com/caochangkui/vue-element-responsive-demo/tree/login-register 通过 vue-cli3.0 + ...

随机推荐

  1. delphi,数据类型,字符、浮点、整数、数组

    字符型:string 浮点型:real 整数:integer DELPHI的浮点数声明不是用float,而是用real(8个字节),single(8个字节,单精度浮点),double(16个字节,双精 ...

  2. cross-origin HTTP request

    w https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS A resource makes a cross-ori ...

  3. 流畅的python 使用一等函数实现设计模式

    案例分析:重构“策略”模式 经典的“策略”模式 电商领域有个功能明显可以使用“策略”模式,即根据客户的属性或订单中的商品计算折扣.假如一个网店制定了下述折扣规则. 有 1000 或以上积分的顾客,每个 ...

  4. Android—Http连接之GET/POST请求

    在Android SDK中提供了Apache HttpClient(org.apache.http.*)模块.在这个模块中涉及到两个重要的类:HttpGet和HttpPost.    创建步骤:    ...

  5. SPL(Standard PHP Library 标准PHP类库)

    SplFileObject 读取大文件从第N行开始读: $line = 10; $splFileObj = new SplFileObject(__FILE__,'r'); $splFileObj-& ...

  6. 004-shiro简介

    一.什么是shiro shiro是apache的一个开源框架,是一个权限管理的框架,实现 用户认证.用户授权. spring中有spring security (原名Acegi),是一个权限框架,它和 ...

  7. pandas(五)处理缺失数据和层次化索引

    pandas用浮点值Nan表示浮点和非浮点数组中的缺失数据.它只是一个便于被检测的标记而已. >>> string_data = Series(['aardvark','artich ...

  8. 算法题 21 findNSum (好未来,LeetCode,牛客网)

    一.三数之和:LeetCode 15 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. ...

  9. Java并发(6):concurrent包中的Copy-On-Write容器

    一. concurrent包介绍 在JDK1.5之前,Java中要进行业务并发时,通常需要有程序员独立完成代码实现,而当针对高质量Java多线程并发程序设计时,为防止死蹦等现象的出现,比如使用java ...

  10. maven的相关命令

    maven的相关命令 mvn archetype:create :创建 Maven 项目 mvn compile :编译源代码(编译到target文件夹中) mvn test-compile :编译测 ...