将Koa v1迁移到v2

问题描述 投票:0回答:3

我在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
  })
javascript node.js koa koa2 koa-router
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)其中ctx在koa2是像this在koa1

参见: 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
  })
© www.soinside.com 2019 - 2024. All rights reserved.