0

I'm using some module with koa and they only have this documentation which is written in koa v1 not v2. and since I've never used v1 before, I have no idea how to write this in 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
  })
Phillip YS
  • 784
  • 3
  • 10
  • 33

3 Answers3

2

Changing from Koa v1 to Koa v2 is a pretty simple process. The only reason for the version bump is that it uses async functions instead of generators for your middleware.

Example v1 Middleware:

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

Example v2 Middleware:

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

use async functions instead of generators, and accept ctx as a parameter instead of using this.

Saad
  • 49,729
  • 21
  • 73
  • 112
  • since I'm really used to koa, I get that part. but I have no idea how to deal with `console.log(this.body.files.foo.path) ` – Phillip YS Jul 15 '17 at 10:25
  • I'm not sure I understand what you mean. It would just be `ctx.body.files.foo.path` instead of `this.body.files.foo.path`. – Saad Jul 15 '17 at 10:27
  • Also, I had an issue in the example v2, I was accidentally still using a genreator instead of an `async` function. fixed now – Saad Jul 15 '17 at 10:29
0

change the function *() to async function(ctx) where ctx in koa2 is like this in koa1

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

Greg Bacchus
  • 2,235
  • 2
  • 23
  • 26
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
  })
Rishabh
  • 185
  • 1
  • 13