我在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
})
从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
。
改变function *()
到async function(ctx)
其中ctx
在koa2是像this
在koa1
参见: http : //koajs.com/#context
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
})