2017-10-10 839 views
0

當我嘗試使用他們的網站koa-route 3.2.0例子,我得到錯誤信息router.routes is not a functionKOA路由器錯誤router.routes不是一個函數

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 

回答

1

看起來你已經安裝了新版本,可在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()); 
+0

並使用'koa-route'而不是'koa-router':/ – Matt

相關問題