Koa

Koa

  1. npm init -y
  2. npm i koa2 --S
  3. package.json 配置启动脚本 "start": "node app.js"
  4. npm i nodemon -g "start": "nodemon app.js"
  5. app.use 参数是中间件,将中间件添加至应用。作用就是调用中间件
    app.use 返回this 也就是app本身
  6. 中间件经常使用async
  7. ctx.body === ctx.response.body
  8. 没有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文件

你可能感兴趣的:(node.js)