简体   繁体   中英

passport.js calling this.somemethod throws TypeError: Cannot read property 'somemethod'

I am calling the following from one class:

router.post('/login', ctrlAuth.login);

Then the ctrlAuth is from another class:

login(req, res) {
    passport.authenticate('ldapauth', function (err, user, info) {
        ... // handling err and !user
        ...
        if (user) this.processUser(req, res);
    })(req, res);
}

private processUser(req, res) {...}

Then I get TypeError: Cannot read property 'processUser' of undefined

So far, this is how I did it, but still doesn't work:

login(req, res) {
    const callback = ((err, user, info) => {
        if (user) this.processUser(req, res);
    }).bind(this);
    passport.authenticate('ldapauth', {session: false}, callback)(req, res);
}

There are two ways I thought of fixing this:

  1. Bind the ctrlAuth to the method:

    router.post('/login', ctrlAuth.login.bind(ctrlAuth));

  2. Create another class and use it as next callback:

    router.post('/login', ctrlAuth.login, ctrlAuth.processUser);

    Inside ctrAuth.login, I call on next();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM