基本功能

实现一个get请求定义

  1. app.use(async(ctx,next)=>{
  2. const { path, method } = ctx
  3. if (path === '/classic' && method === 'GET') {
  4. // ctx.body = 'classic'
  5. // return json
  6. ctx.body = {
  7. key:'classic'
  8. }
  9. }
  10. })

定义路由,并执行函数,定义返回体,写到返回的内容中。

使用第三方路由中间件

  • koa-router ```javascript const koaRouter = require(‘koa-router’) const app = new Koa() const Router = new koaRouter() app.use(async(ctx,next)=>{ const { path, method } = ctx if (path === ‘/classic’ && method === ‘GET’) { // ctx.body = ‘classic’ // return json ctx.body = {
    1. key:'classic'
    } } })

Router.get(‘/classic’, (ctx, next) => { ctx.body = { key:’classic’ } }) app.use(Router.routes()) ``` 基本步骤:1 安装模块并实例化 2 配置路由 3 koa配置实例

小常识

REST风格对几种方法的约定

1 get查询
2 post新增
3 put 更新
4 delete 删除