Ruthless
Ruthless

Reputation: 141

nodeJS/Express TypeError : Cannot read property 'method' of undefined

Hello I am getting an error when trying to start my server. This is what it says :

D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\index.js:139 debug('dispatching %s %s', req.method, req.url); ^

TypeError: Cannot read property 'method' of undefined
    at Function.handle (D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\index.js:139:34)
    at router (D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\index.js:47:12)
    at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\app.js:7:39)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\bin\www:7:11)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47

My app.js file :

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var routes = require('./routes/index')(passport);
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var expressHbs = require('express-handlebars');
var mongoose =require('mongoose');
var app = express();
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var bodyParser = require('body-parser');

mongoose.connect('mongodb://localhost:27017/shopping', {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.connection.on('error', err => {
  throw 'failed to connect to MongoDB';
});
require('D:/Other/Projects/Code/Powershell/shopping-cart/config/passport.js');



// view engine setup
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname:'.hbs'}))
app.set('view engine', '.hbs');

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({secret: 'mysupersecret', resave: false, saveUninitialized: false}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));



app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

And my index.js file :

var express = require('express');
var router = express.Router();
var Product = require('D:/Other/Projects/Code/Powershell/shopping-cart/models/product');
var csrf = require('csurf');
//var passport = require('D:/Other/Projects/Code/Powershell/shopping-cart/config/passport.js');
var passport = require ('passport');
var csrfProtection = csrf();
router.use(csrfProtection);

/* GET home page. */
router.get('/', function(req, res, next) {
  Product.find(function(err, docs) {
    var productChunks = [];
    var chunkSize = 3;
    for (var i = 0; i < docs.length; i += chunkSize) {
           productChunks.push(docs.slice(i, i + chunkSize));
    }
    res.render('shop/index', { title: 'Shopping Cart', products: productChunks });
  });
});

router.get('/user/signup', function (req, res, next) {
   res.render('user/signup', {csrfToken: req.csrfToken()});
});

router.post('/user/signup', passport.authenticate('local.signup', {
  successRedirect: '/user/profile',
  failureRedirect: '/user/signup',
  failureFlash: true
}));

router.get('/user/profile', function(req, res, next) {
  res.render('user/profile');
});

module.exports = router;

Any hints on what could be the issue? I checked the lines that are being mentioned in the thrown error and can not find anything that is broken, and I have also checked other questions on this error, none that helped me. Any help is appreciated , thanks!

Upvotes: 0

Views: 1810

Answers (1)

jfriend00
jfriend00

Reputation: 707986

From the stack trace, it looks like the problem is caused by this line:

var routes = require('./routes/index')(passport);

If you look in your routes/index.js, you are exporting a router with:

module.exports = router;

Well, the problem is that you can't call router(passport). That's not a legit way to use a router. I can't tell what you were really trying to do with that. I would assume you want to hook your routes into the app with something like:

app.use(routes)

But, maybe you had some other intention there. In any case, router(passport) isn't something you can do.


FYI, it is a very useful skill to learn how to read these stack traces. You're typically looking to start at the top of the stack trace and go down line by line until you find a line of code that's in your own source file (your code that triggered this). Then, go examine that exact line with the context of what the eventual error was and see if you can then see what's wrong with that line of code or with the parameters used in that line of code.

Upvotes: 2

Related Questions