Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

router.use TypeError: Cannot read property 'use' of undefined

I'm new to node.js, experts, please help. I'm preparing a code to do user sync based on node.js + AWS Cognito + Facebook Login. I tried an example from this link.

Every step runs smooth until "facebook sing in with passport" section

var express = require('express');
var router = express.Router();
var passport = require('passport');
...
router.use(passport.initialize());
...

After adding this part in the example, I run "npm start", the following error appeared:

C:\workspace\nodejs\CognitoExample\routes\index.js:35
router.use(passport.initialize());
      ^

TypeError: Cannot read property 'use' of undefined

What's the meaning of "Cannot read property"? How to fix the problem? Thank in advance.


After few experts help here, I can solve the problem:

  • re-install express

I used npm install -g express-generator@3 command yesterday, so it make my global setting to express version 3. I uninstall and install express again first.

npm uninstall -g express-generator@3
npm uninstall -g express
npm install -g express
npm install -g express-generator
  • Remove local node_modules

After step 1, same problem is still exist, I found that i installed express 3.x in local working folder before, so I create a new working folder, restart the example code again, problem is gone

like image 959
Edward Pang Avatar asked Oct 16 '15 06:10

Edward Pang


2 Answers

The tutorial you are following is written based on 4.x version of Express framework. There were made significant changes regarding routing process in Express 4.x, comparing with 3.x version. In particular, express.Router() object was added. So, or you have to adept your code (this might help you), in order to make it work, or to upgrade Express versions.

like image 125
Alexandr Lazarev Avatar answered Nov 15 '22 19:11

Alexandr Lazarev


If you are using typescript & es6 imports, and run into the same problem.

use:

import * as passport from "passport";

instead of

import passport from "passport";

refer to: Typescript handbook

like image 31
Vidura Adikari Avatar answered Nov 15 '22 19:11

Vidura Adikari