admin管理员组

文章数量:1303335

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.

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.

Share Improve this question edited Feb 5, 2016 at 16:38 dyachenko 1,21214 silver badges29 bronze badges asked Jul 10, 2015 at 5:54 RickRick 6021 gold badge9 silver badges22 bronze badges 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./alexmingoia/koa-router/issues/120. – James Moore Commented Jul 10, 2015 at 14:57
  • @James Wow. Can be so confusing when trying to learn. Can you post your ment as an answer so I can mark it as answered. Can you also add in what code syntax I should be using instead. – Rick Commented Jul 10, 2015 at 17:44
Add a ment  | 

3 Answers 3

Reset to default 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./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);

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 = {"Wele":"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.

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 :)

本文标签: