koa学习笔记

安装

npm install koa
npm install koa-router
npm install koa-bodyparser
npm install nunjucks

1. hello world

let Koa = require('koa');
let app = new Koa();
app.use(async (ctx,next)=>{
  ctx.response.body = `

hello world

` await next(); }) app.listen(9000) console.log('begin')

app.use([路径],callback)
ctx.body是ctx.response..body的简写
await next()才能继续执行下面的请求

2. koa-router

let Koa = require('koa')
let router = require('koa-router')()
let bodyParser = require('koa-bodyparser')
/*
koa-bodyparser 的作用就是在post请求时,能如下使用
let name = ctx.request.body.name
*/

let app = new Koa();

app.use(bodyParser())

router.get('/',async (ctx)=>{
  ctx.body = '

index

' }) router.get('/about',async (ctx)=>{ ctx.body = '

about

' }) app.use(router.routes()) app.listen(8989)

使用app.use也可以实现不同路径跳转不同界面,但是是要通过从上到下依次判断,还要每个里面都要await next()

3. koa-bodyparser

由于middleware的顺序很重要,这个koa-bodyparser必须在router之前被注册到app对象上。

4. 整合案例

到现在,所有内容都写在app.js中,现在要将他们拆分出来

目录结构
|一级目录|二级
|--|--|--|--|
|controller|hello.js
index.js
...|
|app.js||
|controller.js||

app.js

let Koa = require('koa')
let bodyParser = require('koa-bodyparser')
let controller = require('./controller')

let app = new Koa()

app.use(bodyParser())
app.use(controller())

app.listen(3000)

controller.js

let fs = require('fs')
let router = require('koa-router')()

function addMapping(mapping) {
  for (let url in mapping){
    if(url.startsWith('GET')){
      let path = url.substring(4)
      router.get(path,mapping[url])
    }else if(url.startsWith('GET')){
      let path = url.substring(5)
      router.post(path,mapping[url])
    }
  }
}

function addController(dir) {
  fs.readdirSync(__dirname + '/' + dir).filter(f=>{
    return f.endsWith('.js')
  }).forEach(f=>{
    let mapping = require(__dirname + '/' + dir + '/' + f)
    addMapping(mapping)
  })
}

module.exports = function (dir) {
  let controller_dir = dir || 'controllers';
  addController(controller_dir)
  return router.routes()
}

hello.js

let fn_hello = async ctx => {
  console.log(ctx)
  let name = ctx.params.name
  ctx.body = `

hello ${name},long time no see

` } module.exports = { 'GET /hello/:name': fn_hello }

这样,app.js controller.js 就不需要改动了,需要增加功能在controller文件里面添加js就可以了

addMapping 完整版

function addMapping(router, mapping) {
    for (var url in mapping) {
        if (url.startsWith('GET ')) {
            var path = url.substring(4);
            router.get(path, mapping[url]);
            console.log(`register URL mapping: GET ${path}`);
        } else if (url.startsWith('POST ')) {
            var path = url.substring(5);
            router.post(path, mapping[url]);
            console.log(`register URL mapping: POST ${path}`);
        } else if (url.startsWith('PUT ')) {
            var path = url.substring(4);
            router.put(path, mapping[url]);
            console.log(`register URL mapping: PUT ${path}`);
        } else if (url.startsWith('DELETE ')) {
            var path = url.substring(7);
            router.del(path, mapping[url]);
            console.log(`register URL mapping: DELETE ${path}`);
        } else {
            console.log(`invalid URL: ${url}`);
        }
    }
}

4. 模版引擎nunjucks

npm install nunjucks
4.1 渲染字符串
let nunjucks = require('nunjucks')
nunjucks.configure({autoescape:true})//暂时不知道autoescape拿来干啥用
let res = nunjucks.renderString('{{username}}',{username:'张三'})
console.log(res)
4.2 渲染模版
let nunjucks = require('nunjucks')
let path = require('path')
nunjucks.configure(path.resolve(__dirname,'views'),{autoescape:true})
let res = nunjucks.render('user.html',{name:'张三'})
console.log(res)

需要引入path,读取views文件夹下的user.html

4.3 过滤器
nunjuck.renderString('{{username|join("-")|replace('boy','Man')}}',{username:['boy','sayNo']})
4.4 if
let res = `
{% if score>80 %}
a
{% elseif score>60 %}
b
{% else %}
c
{% endif %}`
nunjucks.renderString(res,{score:80})
4.5 for
{% for item in lists %}
{{item}}*{{loop.index}}
{% endfor %}

和vue的for一样使用,这个多了个loop对象

  • loop.index: 当前循环数 (1 indexed)
  • loop.index0: 当前循环数 (0 indexed)
  • loop.revindex: 当前循环数,从后往前 (1 indexed)
  • loop.revindex0: 当前循环数,从后往前 (0 based)
  • loop.first: 是否第一个
  • loop.last: 是否最后一个
  • loop.length: 总数
4.6模版继承

layout.html

header
{% block my %} 我是默认内容 {% endblock %}

user.html

{% extends "layout.html" %}
{% block my %}
我是用户管理内容
{% endblock %}

app.js里面渲染user.html就会有layout.html的部分。

4.7 包含

include关键字可以引入其他的模版,可以在多模版之间共享一些小模版,如果某个模版已使用了继承那么include将会非常有用。

item.html

  • 名次:{{loop.index}}:{{user.id}}:{{user.name}}
  • user.html

    {% extends "layout.html"%}
    {% block my %}
    
      {% for user in users %} {% include "item.html" %} {% endfor%}
    {% endblock %}
    说明
    __dirname 当前模块的目录名

    你可能感兴趣的:(koa学习笔记)