关于node.js:Koa

10次阅读

共计 1140 个字符,预计需要花费 3 分钟才能阅读完成。

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 文件

正文完
 0