谷歌未处理拒绝ReferenceError发生在使用ES6之后

时间:2018-01-24 03:25:14

标签: javascript node.js es6-promise

我已经完成了一个不使用任何ES6语法的护照系统,一切正常,但是,在我尝试将ES6语法实现到我的代码中之后,比如将'require'转换为'import',我的Google Oauth崩溃并继续显示以下错误消息:

[0] Unhandled rejection ReferenceError: avatar is not defined
[0]     at /Users/labfnp-tw/Documents/ReactNode/auth/Google.js:34:7
[0]     at tryCatcher (/Users/labfnp-tw/Documents/ReactNode/node_modules/bluebird/js/release/util.js:16:23)
[0]     at Promise._settlePromiseFromHandler (/Users/labfnp-tw/Documents/ReactNode/node_modules/bluebird/js/release/promise.js:512:31
)
[0]     at Promise._settlePromise (/Users/labfnp-tw/Documents/ReactNode/node_modules/bluebird/js/release/promise.js:569:18)
[0]     at Promise._settlePromise0 (/Users/labfnp-tw/Documents/ReactNode/node_modules/bluebird/js/release/promise.js:614:10)
[0]     at Promise._settlePromises (/Users/labfnp-tw/Documents/ReactNode/node_modules/bluebird/js/release/promise.js:693:18)
[0]     at Async._drainQueue (/Users/labfnp-tw/Documents/ReactNode/node_modules/bluebird/js/release/async.js:133:16)
[0]     at Async._drainQueues (/Users/labfnp-tw/Documents/ReactNode/node_modules/bluebird/js/release/async.js:143:10)
[0]     at Immediate.Async.drainQueues (/Users/labfnp-tw/Documents/ReactNode/node_modules/bluebird/js/release/async.js:17:14)
[0]     at runCallback (timers.js:789:20)
[0]     at tryOnImmediate (timers.js:751:5)
[0]     at processImmediate [as _immediateCallback] (timers.js:722:5)

我不明白发生了什么,我用'require'立即替换'import',但是,发生了同样的错误信息,所以我在这里遇到两个问题,第一个是我使用ES6模块后发生这些错误的原因,以及为什么在我停止使用ES6模块后仍然无法修复?为了使一切顺利,我在这里发布我的Google Oauth和用户模型代码:

const now = require('date-now');
const passport = require('passport');
const cookieSession = require('cookie-session');
const GoogleStrategy =  require('passport-google-oauth20').Strategy;
const keys = require('../secret/keys.js');
const User = require('../models/User.js');

passport.serializeUser((user, done) => {
  done(null, user.id);
});
passport.deserializeUser((id, done) => {
  User.findById(id).then(user => {
    done(null, user);
  });
});

passport.use(new GoogleStrategy({
  clientID: keys.googleClientID,
  clientSecret: keys.googleClientSecret,
  callbackURL: '/auth/google/callback',
  profileFields: ['id', 'displayName', 'name', 'photos', 'email'],
  proxy: true,
}, (accessToken, refreshToken, profile, done) => {
  User.findOne({ where: { googleID: profile.id } }).then(existinguser => {
    if (existinguser) {
      //Nothing will happen, the ID already exists
      done(null, existinguser);
    }else {
      //Get extra information from Oauth...
      const avatarThumb = profile.photos[0].value;
      const index = profile.photos[0].value.lastIndexOf(50);
      const endpoint = profile.emails[0].value.indexOf('@');
      const username = profile.emails[0].value.substring(0, endpoint);
      avatar = avatarThumb.substr(0, index) + '47' + avatarThumb.substr(index + 1);
      User.create({ username: username,
                    email: profile.emails[0].value,
                    firstname: profile.name.givenName,
                    lastname: profile.name.familyName,
                    googleID: profile.id,
                    displayName: profile.name.givenName + ' ' + profile.name.familyName,
                    avatar: avatar,
                    avatarThumb: profile.photos[0].value,
                    last_login: Date.now(), }).then(user => done(null, user));
    }
  });

}));

用户模型

const Sequelize = require('sequelize');
const mysql = require('mysql');

const User = connection.define('user', {
  username: {
            type: Sequelize.STRING,
            notEmpty: true,
          },

  email: {
            type: Sequelize.STRING,
            validate: {
              isEmail: true,
            },
          },
  firstname: {
            type: Sequelize.STRING,
            notEmpty: true,
          },

  lastname: {
            type: Sequelize.STRING,
            notEmpty: true,
          },
  birthday: {
            type: Sequelize.DATE,
          },

  last_login: {
            type: Sequelize.DATE,
          },

  phone1: {
            type: Sequelize.STRING,
          },

  phone2: {
            type: Sequelize.STRING,
          },

  address: {
            type: Sequelize.STRING,
          },

  address2: {
            type: Sequelize.STRING,
          },

  locale: {
            type: Sequelize.STRING,
            defaultValues: 'zh_TW',
          },

  googleID: {
    type: Sequelize.STRING,
  },

  facebookID: {
    type: Sequelize.STRING,
  },

  displayName: {
    type: Sequelize.STRING,
  },

  username: {
    type: Sequelize.TEXT,
  },

  rolesArray: {
    type: Sequelize.VIRTUAL,

    // get() {
    //   try {
    //     const thisRoles = this.getDataValue('Roles');
    //     const roles = thisRoles ? thisRoles.map(role => role.authority) : [];
    //     return roles;
    //   } catch (e) {
    //     sails.log.error(e);
    //   }
    // },
  },
  userAgent: {
    type: Sequelize.STRING,
  },
  lastLoginIP: {
    type: Sequelize.STRING,
  },
  lastLoginLat: {
    type: Sequelize.DOUBLE,
  },
  lastLoginLng: {
    type: Sequelize.DOUBLE,
  },

  avatar: {
    type: Sequelize.STRING,
  },

  avatarThumb: {
    type: Sequelize.STRING,
  },

  score: {
    type: Sequelize.INTEGER,
    defaultValue: 0,
  },

  resetPasswordToken: {
              type: Sequelize.STRING(32),
            },

  verificationEmailToken: {
              type: Sequelize.STRING(32),
            },

  password: {
          type: Sequelize.STRING,
        },
});

connection.authenticate().then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

module.exports = User;

1 个答案:

答案 0 :(得分:1)

我看到的一个明显问题是在设置之前未定义avatar。尝试使用const

声明它