Edward Pang
Edward Pang

Reputation: 101

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:

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

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

Upvotes: 7

Views: 17151

Answers (3)

Vidura Adikari
Vidura Adikari

Reputation: 648

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

Upvotes: 1

Deke
Deke

Reputation: 4649

I ran into similar problem. I placed the code after app.use(express.static...) and it worked.

Upvotes: -1

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12882

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.

Upvotes: 6

Related Questions