使用KoaJS和PassportJS自动登录用户

时间:2015-05-26 02:33:50

标签: javascript node.js passport.js koa koa-passport

我尝试使用PassportJS自动登录用户。

这是我目前的代码:

myRouter.get('/signin', function* (next) {

    user = {...};

    var res = this.res; // needed for the function below
    this.req.login(user, function(err) {
        if (err)
            console.log('error logging in user - '+err);
        return res.redirect('/'); // <--- line 439
    });
});

但是当我运行它时,我收到错误:

  error logging in user - TypeError: undefined is not a function
  TypeError: undefined is not a function
      at /srv/www/domain.com/app.js:439:32
      at /srv/www/domain.com/node_modules/koa-passport/node_modules/passport/lib/http/request.js:49:48
      at pass (/srv/www/domain.com/node_modules/koa-passport/node_modules/passport/lib/authenticator.js:293:14)
      at Authenticator.serializeUser (/srv/www/domain.com/node_modules/koa-passport/node_modules/passport/lib/authenticator.js:295:5)
      at Object.req.login.req.logIn (/srv/www/domain.com/node_modules/koa-passport/node_modules/passport/lib/http/request.js:48:29)
      at Object.<anonymous> (/srv/www/domain.com/app.js:434:26)
      at GeneratorFunctionPrototype.next (native)
      at Object.dispatch (/srv/www/domain.com/node_modules/koa-router/lib/router.js:317:14)
      at GeneratorFunctionPrototype.next (native)
      at Object.<anonymous> (/srv/www/domain.com/node_modules/koa-common/node_modules/koa-mount/index.js:56:23)

2 个答案:

答案 0 :(得分:0)

一个快速的半derp时刻,我意识到要在koa重定向它不使用resthis,您必须执行以下操作:

var res = this; // needed for the next function
this.req.login(user, function(err) {
    if (err)
        console.log('error logging in user - '+err);
    return res.redirect('/');
});

答案 1 :(得分:0)

您的代码很好,只是res被称为response,所以只需更改即可 var res = this.res;var res = this.response;,它会正常工作。 res确实存在,但它是Node http模块响应,而不是Koa Response对象,因此没有任何redirect方法。 redirect的别名为this,这就是您可以使用this.redirect的原因,但它确实是Response方法。 有关详细信息,请查看http://koajs.com/#context

为了避免分配thisresponse,您可以将this绑定到您的函数,我认为在大多数情况下它更干净:

myRouter.get('/signin', function* (next) {

    user = {...};

    this.req.login(user, function(err) {
        if (err)
            console.log('error logging in user - '+err);
        return this.redirect('/'); // <--- line 439
    }.bind(this));
});
相关问题