首页 文章

将koa v1迁移到v2

提问于
浏览
0

我正在使用koa的一些模块,他们只有这个用koa v1而不是v2编写的文档 . 因为我之前从未使用过v1,所以我不知道如何在v2中编写这个 .

app
  .use(body({
    IncomingForm: form
  }))
  .use(function * () {
    console.log(this.body.user) // => test
    console.log(this.request.files) // or `this.body.files`
    console.log(this.body.files.foo.name) // => README.md
    console.log(this.body.files.foo.path) // => full filepath to where is uploaded
  })

3 回答

  • 1

    从Koa v1更改为Koa v2是一个非常简单的过程 . 版本颠簸的唯一原因是它使用 async 函数而不是中间件的生成器 .

    示例v1中间件:

    app.use(function* (next) {
      yield next
      this.body = 'hello'
    })
    

    示例v2中间件:

    app.use(async (ctx, next) => {
      await next()
      ctx.body = 'hello'
    })
    

    使用 async 函数代替生成器,并接受 ctx 作为参数而不是使用 this .

  • 0

    function *() 更改为 async function(ctx) ,其中koa2中的 ctx 与koa1中的 this 相似

    见:http://koajs.com/#context

  • 0
    app
      .use(body({
        IncomingForm: form
      }))
      .use(function(ctx) {
        console.log(ctx.body.user) // => test
        console.log(ctx.request.files) // or `this.body.files`
        console.log(ctx.body.files.foo.name) // => README.md
        console.log(ctx.body.files.foo.path) // => full filepath to where is uploaded
      })
    

相关问题