使用 KoaJS 和 PassportJS 自动登录用户

Automatically logging in a user with KoaJS and PassportJS

我正在尝试使用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)

一个快速的 semi-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('/');
});

你的代码没问题,就是res调用了response,改一下就行了 var res = this.res;var res = this.response; 中,它将正常工作。 res 确实存在,但它是 Node http 模块响应,而不是 Koa Response 对象,因此没有任何 redirect 方法。 redirectthis 的别名,这就是为什么您可以使用 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));
});