Koa
- npm init -y
- npm i koa2 --S
- package.json 配置启动脚本 "start": "node app.js"
- npm i nodemon -g "start": "nodemon app.js"
- app.use 参数是中间件,将中间件增加至利用。作用就是调用中间件
app.use 返回this 也就是app自身 - 中间件常常应用async
- ctx.body === ctx.response.body
没有webpeck 翻译请不要应用import
洋葱模型
与express 不同 express是所有中间件程序执行完结后响应.koa遇见next后会跳出以后中间件,执行下一个中间件,直到没有next 而后回到上一个中间件执行next之后的代码,直到第一个
app.use(async (ctx, next)=> { console.log(1); ctx.body='222'; await next(); // 想输入1 必须期待下面的next完结 记得画图 console.log(1); }) .use(async (ctx, next)=> { console.log(2); await next() console.log(2); }) .use(async (ctx, next)=> { console.log(3); await next() console.log(3); })//输入 1 2 3 2 1
中间件
1) 路由中间件 npm i koa-router
// app 入口文件const Koa = require('koa2');const Router = require('koa-router');// 申明利用const app = new Koa();const router = new Router();router.get('/', async ctx => { ctx.body = 'router'})// 注册中间件 router.routes()启动路由 router.allowedMethods()容许任意申请app.use(router.routes(), router.allowedMethods()) .listen (9000,()=>{ console.log('serve start.....111'); })
2) 路由重定向
路由入口文件中书写
router.redirect('/', '/home') 参数1 用户输出的 参数2是重定向的
3) 子路由
路由入口文件中书写
router.use ('/list', 第一层子路由list.routes(),list.allowedMethods())
4) 404有效路由
5) 错误处理
我的项目拆解
app.js 是入口文件,外面不要写路由的货色。创立一个路由文件夹,然而路由文件也须要拆分,index.js是路由的入口,只做重定向,其余的路由定义不同的js文件