vue+koa 美团实战之koa基础

koa-generator使用

安装全局脚手架: npm i -g koa-generator

使用: koa2 -e koa2-learn

cd koa2-learn

npm install

npm i --update-binary

npm run dev

async / await 的使用

声明了async , 可以没有await , 反之则不可以。

router.get('/testAsync', async (ctx) => {
  global.console.log('start', new Date().getTime());
  let a = await new Promise((resolve, reject) => {
    setTimeout(function() {
      global.console.log('start', new Date().getTime());
      resolve('a')
    }, 3000)
  })
  ctx.body = {
    a
  }
})

注意两点:

  1. 有多个await的时候, 自上而下执行
  2. await后面跟的是一个promise对象, 如果不是, 就会自动转换.

比如说: let a = await '3' === let a = await Promise.resolve('3')

koa2 中间件机制

引入核心包koa => 创建koa实例 => 使用中间件

写入顺序和输出顺序相反

实现几个简单中间件

function pv(ctx) {
  global.console.log('pv' + ctx.path);
}

module.exports = function() {
  return async function(ctx, next) {
    pv(ctx);   //执行操作
    await next(); // 这一步很重要, 等待执行完毕, 交给下一个中间件
  }
}

疑问: ctx 是什么?

答:在中间件机制中, 服务端有一个对象, 挂载了response和request. 这个对象就是ctx.

疑问: 什么是洋葱圈机制?
答:

koa.use(m1);
koa.use(m2);
koa.use(m3);

执行如下: 
-----------------

start m1
start m2
start m3

end m3
end m2
end m1

koa 路由

使用:

const router = require('koa-router')()
//render渲染
router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})
//body 写给客户端
router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

//导出
module.exports = router

app.js使用:

const index = require('./routes/index')
const users = require('./routes/users')
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())


cookie

问题: 如何读写cookie?

写: ctx.cookies.set('pvid', Math.random())
读: cookie: ctx.cookies.get('pvid')

猜你喜欢

转载自blog.csdn.net/weixin_40814356/article/details/83053536
koa