Using 'koa-router', app.use(router(app)) throws a "requires a generator function" error msg
Asked Answered
P

3

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.

Pronouncement answered 10/7, 2015 at 5:54 Comment(2)
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 github.com/alexmingoia/koa-router/issues/120.Avenge
@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.Pronouncement
A
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);
Avenge answered 10/7, 2015 at 18:44 Comment(2)
Thanks and thanks for your great koa learning videos on YouTube! linkPronouncement
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 github.com/alexmingoia/koa-router/issues/207Zest
S
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.

Sheared answered 10/7, 2015 at 14:31 Comment(0)
M
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 :)

Mcclish answered 10/7, 2015 at 14:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.