palo
palo

Reputation: 169

How to solve "cannot read property 'push' of undefined in node.js

I have two files one is 'a.js' in compressed folder and another b.js in a folder b within compressed folder and i am using routing of express.i am a beginner and don't know how to resolve this error and what does it mean.I want to use b file in a.js. a.js

```var express = require('express');
var path = require('path');
var app = express();
var route=require("./b/b");
app.use("/b",route);
app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/btn.html'));
});

app.post('/c', function (req, res,next) {
  console.log('ist MD');
  next();
});
app.post('/c', function (req, res,next) {
  console.log('snd MD');
  next();
});
app.post('/c', function (req, res,next) {
  console.log('third MD');

});

app.listen(3000);

here is b.js

   const express=require("express"); 
const Router=express.Router; 
Router.get('/',(req,res)=>{ console.log("i am file b");
 });
 module.export=Router;

This is error

C:\Users\Palwasha\Downloads\Compressed\b\node_modules\express\lib\router\index.js:502

this.stack.push(layer); ^

TypeError: Cannot read property 'push' of undefined at Function.route (C:\Users\Palwasha\Downloads\Compressed\b\node_modules\express\lib\router\index.js:502:14) at Function.proto.(anonymous function) [as get] (C:\Users\Palwasha\Downloads\Compressed\b\node_modules\express\lib\router\index.js:509:22) at Object. (C:\Users\Palwasha\Downloads\Compressed\b\b.js:3:9) at Module._compile (internal/modules/cjs/loader.js:778:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) at Module.require (internal/modules/cjs/loader.js:692:17) at require (internal/modules/cjs/helpers.js:25:18)

Upvotes: 0

Views: 937

Answers (1)

James
James

Reputation: 82096

You need to create & reference an instance of Router

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

router.get('/',(req,res)=>{ console.log("i am file b"); });

module.exports = router;

Upvotes: 1

Related Questions