1

当我尝试使用他们网站上的koa-route 3.2.0 示例时,我收到错误消息router.routes is not a function

const Koa = require('koa');
const router = require('koa-route');

const app = new Koa();
app.use(logger());

router.get('/users', (ctx, next) => {
    ctx.response.body =`<h1>Hello!</h1>`;
});

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

// don't listen to this port if the app is required from a test script
if (!module.parent) {
  app.listen(1337);
  console.log('listening on port: 1337');
}

我收到错误消息:

app.use(router.routes())
               ^

TypeError: router.routes is not a function
    at Object.<anonymous> (/Projects/shoucast-front-end-prototype/script/server.js:40:16)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3

当我试图改变

const router = require('koa-route');

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

我收到错误消息:

const router = require('koa-route')();
                                   ^

TypeError: require(...) is not a function
    at Object.<anonymous> (/Projects/shoucast-front-end-prototype/script/server.js:2:36)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3
4

1 回答 1

3

看起来您已经安装了较新的版本,可在https://github.com/alexmingoia/koa-router/tree/master获得

你需要new Router()改用。

看起来你也在混淆koa-routerkoa-route这是两个不同的包。

const Koa = require('koa');
const Router = require('koa-router');

const app = new Koa();
const router = new Router();

router.get('/', function (ctx, next) {
  // ctx.router available
});

app
  .use(router.routes())
  .use(router.allowedMethods());
于 2017-10-10T15:32:52.743 回答