网址 https://koa.bootcss.com
koa2是一个服务端的框架。
安装
npm install -g koa-generator
install dependencies:
cd koa2-learn && npm install
run the app:
DEBUG=koa2-learn:* npm start
创建项目:koa2 project
使用npm run dev可以实现更改后的代码自启动
//脚本配置文件 package.json
"scripts": {
"start": "node bin/www",
"dev": "./node_modules/.bin/nodemon bin/www",
"prd": "pm2 start bin/www",
"test": "echo \"Error: no test specified\" && exit 1"
}
注意:在命令行中可以使用npm start / npm test,但对于另外两条命令只能用npm run dev / npm run prd。
koa异步 async和await的用法
async和await是实现异步的方式。实现异步的方式在不断更新,从一开始的回调函数,到promise链式调用,再到async和await用法。
注意:如果外层没有async函数,那么内层是不允许使用await的。外层有async,内层可以没有await。
async和await用同步操作的写法完成异步操作的过程,这一点与promise的.then链式操作不同。这可以使得代码结构清晰。
await后面跟的是promise对象,如果不是一个promise对象,系统也会将其转换成一个promise对象。
//index.js文件
const router = require('koa-router')()
router.get('/', async (ctx, next) => {
global.console.log('index2')//这里的global好像是linux里类似于windows的存在
await ctx.render('index', {
title: 'Hello Koa 2!'
})
})
router.get('/string', async (ctx, next) => {
ctx.body = 'koa2 string'
})
router.get('/json', async (ctx, next) => {
ctx.body = {
title: 'koa2 json'
}
})
router.get('/testAsync',async(ctx) => {
global.console.log('start',new Date().getTime())
const b = await new Promise((resolve,reject)=>{
setTimeout(function(){
global.console.log('async a',new Date().getTime())
resolve('a')
// 上面这一句的意思是异步任务完成时返回'a'
},1000);
})
// 有await在的时候,上面这一段执行完了之后才会执行下面的内容,这时候页面可以显示异步操作之后返回的内容。如果没有await的话,页面显示不了'a'.
// 这就是await和async连用实现链式异步操作。但是看起来像是同步操作的写法,所以看起来很直观。
// const cc=await 123
// const cc=await Promise.resolve(123)
// 上面两句的效果完全相同
ctx.body={
b,
// cc
}
// 如果上面这一段里用了await,则页面显示{"b":"a"},如果没有await,则页面显示{"b":{}}
})
module.exports = router
koa2中间件
const Koa = require('koa')
const app = new Koa() //新建koa对象
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const index = require('./routes/index')
const users = require('./routes/users')
//使用requier方法引入中间件
// error handler
onerror(app)
// middlewares
app.use(bodyparser({
enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
//使用use方法使用中间件,在使用的时候没有先后顺序
手写中间件
//koa-pv.js
function pv(ctx){
global.console.log('pv:',ctx.path)
}
module.exports=function(){
return async function(ctx,next){
pv(ctx)
await next()
// 这一句表示当前中间件处理完毕,请交给下一个中间件处理
}
}
//app.js
const pv=require('./middleware/koa-pv')
app.use(pv())
koa路由
路由的写法
接口举例
const router = require('koa-router')()
router.prefix('/users')
//所有路径前加前缀,方便模块化开发
router.get('/', function (ctx, next) {
ctx.body = 'this is a users response!'
})
router.get('/bar', function (ctx, next) {
ctx.body = 'this is a users/bar response'
})
module.exports = router
//最后需要导出
cookie和session
参考文档同koa参考文档
cookie和session的定义
cookie和session的作用
const router = require('koa-router')()
router.get('/', async (ctx, next) => {
global.console.log('index2')
ctx.cookies.set('pvid', Math.random())
// 写cookie
await ctx.render('index', {
title: 'Hello Koa 2!'
})
})
router.get('/string', async (ctx, next) => {
ctx.body = 'koa2 string'
})
router.get('/json', async (ctx, next) => {
ctx.body = {
title: 'koa2 json',
cookie: ctx.cookies.get('pvid')
// 读cookie
}
})
module.exports = router