无法读取' get'在快速路由器中未定义

时间:2017-05-08 10:34:14

标签: node.js

我的代码如下所示:

app.js

const app = express();
const itemsRouter = require('./routes/items.js');

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use('/items', itemsRouter);

items.js

const router = require('express').router;

router.get('/itemTest', (req, res) => {
    res.json({
        sucess: true
    });

    console.log(`the parametrs are ${req.body.item_name}  ${req.body.item_post}`);
});

module.exports = router;

但是在某种程度上,我无法让路由器正常工作,而且它说无法读取属性' get'未定义的。

错误堆栈如下所示:

TypeError: Cannot read property 'get' of undefined
    at Object.<anonymous> (C:\Users\anand\quFlipApi\routes\items.js:5:7)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\anand\quFlipApi\app.js:33:19)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)

1 个答案:

答案 0 :(得分:4)

这里有两个问题:

  1. 它是express.Router而不是express.router
  2. 您需要创建express.Router的新实例(例如var router = new express.Router()),而不是尝试直接将构造函数用作实例。