Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot read property of 'get' undefined in the express router

Tags:

node.js

My code is as shown below:

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;

But here somehow, I am not able to get the router working and it says that can not read property 'get' of undefined.

the error stack is as shown below:

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)
like image 374
M thaker Avatar asked Mar 09 '23 03:03

M thaker


1 Answers

There are two problems here:

  1. It's express.Router and not express.router.
  2. You need to create a new instance of express.Router (e.g. var router = new express.Router()) instead of trying to using the constructor directly as an instance.
like image 199
mscdex Avatar answered May 18 '23 21:05

mscdex