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

17,015

Solution 1

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.

Solution 2

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

Share:
17,015
Admin
Author by

Admin

Updated on July 01, 2022

Comments

  • Admin
    Admin almost 2 years

    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