使用KoaJS和PassportJS自动登录用户 [英] Automatically logging in a user with KoaJS and PassportJS

查看:124
本文介绍了使用KoaJS和PassportJS自动登录用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PassportJS 自动登录用户.

I'm trying to automatically log in a user with 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
    });
});

但是当我运行它时,出现错误:

But when I run it, I get the error:

  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)

推荐答案

一个简短的半derp瞬间,我意识到要在koa中重定向,它不使用res而是使用this,您必须执行以下操作:

A quick semi-derp moment and I realize to redirect in koa it does not use res but this, you must do the following:

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('/');
});

这篇关于使用KoaJS和PassportJS自动登录用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆