6
var app = require('koa')();
var router = require('koa-router');

app.use(router(app));

Throws this error:

AssertionError: app.use() requires a generator function

A lot of sample code says to setup koa-router this way. It supposedly adds methods to the koa app.

dyachenko
  • 1,216
  • 14
  • 28
Rick
  • 572
  • 1
  • 7
  • 21
  • The koa-router package changed a few months back and removed the functionality to extend the app object, as you've coded above... It used to work that way, but it was a breaking change https://github.com/alexmingoia/koa-router/issues/120. – James Moore Jul 10 '15 at 14:57
  • @James Wow. Can be so confusing when trying to learn. Can you post your comment as an answer so I can mark it as answered. Can you also add in what code syntax I should be using instead. – Rick Jul 10 '15 at 17:44

3 Answers3

7

The koa-router package changed a few months back and removed the functionality to extend the app object, as you've coded above... It used to work that way, but it was a breaking change:

http://github.com/alexmingoia/koa-router/issues/120.

Here is an example of how you setup routes now:

var app = require('koa')();
var router = require('koa-router');

// below line doesn't work anymore because of a breaking change
// app.use(router(app));

var api = router();

api.get('/', function *(){
    this.body = 'response here';
});

app
  .use(api.routes())
  .use(api.allowedMethods());

app.listen(3000);
James Moore
  • 1,881
  • 14
  • 18
  • Thanks and thanks for your great koa learning videos on YouTube! [link](https://www.youtube.com/channel/UC4nNCN49Fxexd30qtbzPDkg) – Rick Jul 10 '15 at 21:10
  • 1
    Please note that the newer versions of koa-router will have the exact problem as OP if you use the code above. This is because koa-router has moved to koa2. Using an older koa-router may solve the issue. See https://github.com/alexmingoia/koa-router/issues/207 – RajV Jan 11 '17 at 09:26
1

First, change your:

var router = require('koa-router');

to

var router = require('koa-router')();

After that, insert some router rule, for example:

router.get('/', function *(next) {
  this.status = 200;
  this.body = {"Welcome":"Hello"};
});

And at the end of all this write: app.use(router.routes()); - this line is a key factor here... And you're all set.

jwitos
  • 492
  • 3
  • 7
  • 24
0

It won't work because app is an object. Try setting up your router like:

var app = require('koa')();
var Router = require('koa-router');
var pub = new Router();
app.use(pub.routes());

Hope this clears you up :)

Jake
  • 2,515
  • 5
  • 26
  • 41
Rei Dien
  • 196
  • 13