首页 > 解决方案 > 面临护照js的问题

问题描述

我是节点 js 的新手,我正在尝试使用谷歌护照做一个授权示例,下面是我的代码:

index.js

const express = require('express');
const app = express();
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(new GoogleStrategy({
      clientID        : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      clientSecret    : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      callbackURL     : "http://localhost/google/login",
      passReqToCallback   : true
  },
  function(accessToken, refreshToken, profile, done) {
    return done(); //this is the issue, I am confused with it's use
  }
));

app.get('/failed', function (req, res) {
  res.send('failed login')
});

app.get('/final', function (req, res) {
  res.send('finally google auth has done')
});

app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile'] }));

app.get('/google/login',
  passport.authenticate('google', { failureRedirect: '/failed' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/final');
  });

app.listen('80', () => {
  console.log('server is running')
})

最后,我的目标是在不检查数据库的值的情况下成功登录谷歌,因为我只是在学习它。

节点索引.js

然后我打开网址:http://localhost/auth/google

我的程序应该get /final在使用谷歌凭据登录后运行,但出现错误TypeError: done is not a function

我没有得到使用,done()我该如何解决它。

标签: node.jspassport.jspassport-google-oauthpassport-google-oauth2

解决方案


使用时passReqToCallback : true,需要更改回调函数的参数。req也需要作为回调函数的第一个参数传递。

你的回调函数参数应该是(req, accessToken, refreshToken, profile, done)

这就是您收到错误的原因:

done 不是函数

尝试这个 :

passport.use(new GoogleStrategy({
      clientID        : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      clientSecret    : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      callbackURL     : "http://localhost/google/login",
      passReqToCallback   : true
  },
  function(req, accessToken, refreshToken, profile, done) {
    return done(); // it will work now
  }
));

推荐阅读