Koa和Nunjucks的API使用总结

一、Koa的使用:

//1.导入Koa模块. 注Koa2开始, 导入的是一个class
const Koa = require('koa');
//2.创建Koa对象
const app = New Koa();
//3.调用异步执行的方法, 处理网络请求
app.use(async (ctx, next) => {
    await next();//执行next则会跳转执行下一个middleware
    ctx.response.type = 'text/html';
    ctx.response.body = '

Hello, koa2!

'; }); //4.绑定端口监听 app.listen(3000); console.log('app started at port 3000...');

二、Koa-router处理不同URL

const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');//用来处理post请求的json数据,注:在router被注册到app之前执行
//1.引入,引入的接口是一个函数, 下面选择直接执行函数获得router对象
const router = require('koa-router')();
//2.接收网络请求, 执行下一个middleware
app.use(async (ctx, next) => {
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
    await next();
});
app.use(bodyParser());//注册bodyParser用来处理json解析
//3.使用router匹配url get请求
router.get('/hello/:name', async (ctx, next) => {
    var name = ctx.params.name;
    ctx.response.body = `

Hello, ${name}!

`; }); router.get('/',async(ctx, next)=>{ ctx.response.body = '

Index

'; }); //post请求 router.post('/signin', async (ctx, next) => { var name = ctx.request.body.name || '', password = ctx.request.body.password || ''; console.log(`signin with name: ${name}, password: ${password}`); if (name === 'koa' && password === '12345') { ctx.response.body = `

Welcome, ${name}!

`; } else { ctx.response.body = `

Login failed!

Try again

`; } }); //4.把routers添加进middleware app.use(router.routes()); app.listen(3000); console.log ('app started at port 3000...')

三、Nunjucks的使用

const nunjucks = require('nunjucks');
//1.定义函数用于使用nunjucks对象创建environment
function createEnv(path, opts) {
    var
        autoescape = opts.autoescape && true,
        noCache = opts.noCache || false,
        watch = opts.watch || false,
        throwOnUndefined = opts.throwOnUndefined || false,
        env = new nunjucks.Environment(
            new nunjucks.FileSystemLoader('views', {
                noCache: noCache,
                watch: watch,
            }), {
                autoescape: autoescape,
                throwOnUndefined: throwOnUndefined
            });
    if (opts.filters) {
        for (var f in opts.filters) {
            env.addFilter(f, opts.filters[f]);
        }
    }
    return env;
}
//2.创建environment
var env = createEnv('views', {
    watch: true,
    filters: {
        hex: function (n) {
            return '0x' + n.toString(16);
        }
    }
});
//3.使用environment对象渲染html文件
     //注:html文件放在views目录下
var s = env.render('hello.html', { name: '小明' });
console.log(s);

四、Koa-router框架注册url, 以及配合Nunjucks框架的MVC封装

参考:廖雪峰JavaScript教程
Nunjuncks官方文档

你可能感兴趣的:(Koa和Nunjucks的API使用总结)