Koa

Koa

const Koa = require('koa');
const app = new Koa();
const Koa = require('koa');
const router = require('koa-router')();//路由中间件
const views = require('koa-views');//ejs 中间件   
const bodyParser  = require('koa-bodyparser'); //获取提交中间件
const static = require('koa-static');//静态资源中间件
const path = require('path');
const session = require('koa-session');

var app = new Koa();
app.use(bodyParser());
app.use(static(__dirname + '/static'));

//art_template 模板引擎 比ejs 速度快
//http://aui.github.io/art-template/koa/
/**
 * npm install --save art-template
 * npm install --save koa-art-template
 * 
 * conset render = require('koa-art-template');
 * 
 * render(app, {
 *  root: path.join(__dirname, 'views'),//视图位置
 *  extname: '.html', //后缀名
 *  debug: process.env.NODE_ENV !== 'production' //是否开启调试模式
 *  
 * })
 * 
 * **/

 //koa cookie 保存在浏览器客户端
 /**
    ctx.cookies.set(name, value, [options]);
    //设置中文 new Buffer("中文").toString('base64');
    ctx.cookies.get();
    

    通过 options 设置 cookie name 的 value :
    maxAge 一个数字表示从 Date.now() 得到的毫秒数
    signed cookie 签名值
    expires cookie 过期的 Date
    path cookie 路径, 默认是'/'
    domain cookie 域名
    secure 安全 cookie 默认false ,设置成true 表示只有在https可以访问
    httpOnly 服务器可访问 cookie, 默认是 true
    overwrite 一个布尔值,表示是否覆盖以前设置的同名的 cookie (默认是 false). 
    如果是 true, 在同一个请求中设置相同名称的所有 Cookie(不管路径或域)是否在设置此Cookie 时从 Set-Cookie 标头中过滤掉。
 
  * **/

  //koa session  
  /**
   * 基于cookie
   * $ npm install koa-session
   * 
   * 
   */
  
  app.keys = ['some secret hurr'];//cookie 签名
  
  const CONFIG = {
    key: 'koa:sess', /** (string) cookie key (default is koa:sess) */
    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: true, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
  };
  
  app.use(session(CONFIG, app));
  // or if you prefer all default config, just use => app.use(session(app));
  //end





//中间件 访问都会先打印日期
app.use(async (ctx, next) => {
    //公共信息
    ctx.state = {
        'username': 'zbx',
        'password': '123456'
    }

    console.log(new Date());
    console.log(ctx);
    await next();

    console.log(ctx);
    //错误处理
    if(ctx.status === 404){
        ctx.body = "页面404";
    }else{
        console.log('200');
    }
})

//ejs 模板
app.use(views('views', {
    extension:'ejs'
}))

router.get('/', async(ctx, next) => {
    
    let list = new Array('a', 'b', 'c', 'd');
    let title = "this is title";
    let content = "<h3>this is html</h3>";

    await ctx.render('index', {
        title: title,
        list: list,
        content: content,
        username: ctx.state.username
    });
})

router.get('/news', async(ctx, next) => {
    //http://localhost:3008/news?aid=123&name=zbx
    //ctx.query: 返回  { aid: '123', name: 'zbx' }
    //ctx.querystring: 返回  aid=123&name=zbx
    ctx.body = '新闻页面';
})

//动态路由
//router.get('/newscontent/:aid:cid', async(ctx, next) => {
router.get('/newscontent/:aid', async(ctx, next) => {
    console.log(ctx.params);
    ctx.body = '新闻详情';
})

router.post('/login', async(ctx, next) => {
    ctx.body = ctx.request.body;
})

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

app.listen(3008, () => {
    console.log('server by 3008')
});

转载于:https://my.oschina.net/zhubaoxin/blog/2960811

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值