Closed pensierinmusica closed 9 years ago
dose this meet your needs?
@dead-horse, I tried a similar solution before, but probably I did something wrong since it returns an error.
Here's an example of the code:
var app = require('koa')();
var router = require('koa-router')();
var bodyParser = require('koa-bodyparser');
router.post('/', function* () {
yield bodyParser();
this.body = this.request.body;
});
app.use(router.routes());
app.listen(3000);
And the error:
TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined at Object.bodyParser
Could you please help me in figuring out what I'm doing wrong / how to fix it?
Thanks!
var koa = require('koa')
var router = require('koa-router')()
var bodyparser = require('koa-bodyparser')
var app = koa()
router.post('/', bodyparser(), function* () {
this.body = this.request.body
})
app.use(router.routes()).listen(3000)
@dead-horse, I see, thanks!
Could you help me understand a bit better what is the difference between my initial version and your version, or point me in the right direction?
Also, I'd prefer "yielding" the body parser inside a generator function, so I can choose exactly when to do it (for example, after checking some headers). The approach is similar to the one shown here, using koa-body-parsers, where you can do something like:
app.use(function* (next) {
// Some code
var body = yield this.request.json();
// Some other code
yield next;
});
Is there any way to achieve this with koa-bodyparser
?
bodyparser()
return a koa middleware, so if you want to "yielding" the body parser inside a generator function, you can just use co-body
Sure, that makes sense, thanks!
Is it possible to use
koa-bodyparser
in connection withkoa-router
and parse the request body only on some routes? If so, what is the best way to do it? Thanks!