koajs / bodyparser

Koa body parsing middleware
MIT License
1.31k stars 117 forks source link

Parse body only on some routes #21

Closed pensierinmusica closed 9 years ago

pensierinmusica commented 9 years ago

Is it possible to use koa-bodyparser in connection with koa-router and parse the request body only on some routes? If so, what is the best way to do it? Thanks!

dead-horse commented 9 years ago

dose this meet your needs?

pensierinmusica commented 9 years ago

@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!

dead-horse commented 9 years ago
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)
pensierinmusica commented 9 years ago

@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?

dead-horse commented 9 years ago

bodyparser() return a koa middleware, so if you want to "yielding" the body parser inside a generator function, you can just use co-body

pensierinmusica commented 9 years ago

Sure, that makes sense, thanks!