Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

koa

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.

like image 783
Rick Avatar asked Jul 10 '15 05:07

Rick


2 Answers

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);
like image 163
James Moore Avatar answered Sep 29 '22 11:09

James Moore


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.

like image 26
jwitos Avatar answered Sep 29 '22 10:09

jwitos