首页 > 解决方案 > 尝试注册新用户或登录时出错

问题描述

出于某种原因,每当我向路由发出请求以创建新用户时,尽管已创建用户,但我得到“此电子邮件帐户已在使用中”,当我尝试登录时,我得到“登录信息不正确”。我在登录时控制台记录了 req.body 并记录了对象,看起来还不错。

我的 AuthenticationController.js

const {User} = require('../models')
const jwt = require('jsonwebtoken')
const config = require('../config/config')

function jwtSignUser (user) {
  const ONE_WEEK = 60 * 60 * 24 * 7
  return jwt.sign(user, config.authentication.jwtSecret, {
    expiresIn: ONE_WEEK
  })
}

module.exports = {
  async register (req, res) {
    try {
      const user = await User.create(req.body)
      const userJson = user.toJSON()
      res.send({
        user: userJson,
        token: jwtSignUser(userJson)
      })
    } catch (err) {
      res.status(400).send('This email account is already in use.')
    }
  },
  async login (req, res) {
    console.log(req.body)
    try {
      const {email, password} = req.body
      const user = await User.findOne({
        where: {
          email: email
        }
      })

      if (!user) {
        return res.status(403).send({
          error: 'The login information was incorrect'
        })
      }

      const isPasswordValid = await user.comparePassword(password)
      if (!isPasswordValid) {
        return res.status(403).send({
          error: 'The login information was incorrect'
        })
      }

      const userJson = user.toJSON()
      res.send({
        user: userJson,
        token: jwtSignUser(userJson)
      })
    } catch (err) {
      res.status(500).send({
        error: 'An error has occured trying to log in'
      })
    }
  }
}

console.log(user) 给了我以下信息:

User {
  dataValues:
   { id: 41,
     username: 'testing',
     email: 'testing@gmail.com',
     password:
      '$2a$08$J6/psKuCltiCpCll2rjz4OaCylud0zq/wKnjKK8Udmm.bFU3c2Tt6',
     firstName: 'test',
     lastName: 'ing',
     createdAt: 2019-02-26T15:47:09.133Z,
     updatedAt: 2019-02-26T15:47:09.133Z },
  _previousDataValues:
   { id: 41,
     username: 'testing',
     email: 'testing@gmail.com',
     password:
      '$2a$08$J6/psKuCltiCpCll2rjz4OaCylud0zq/wKnjKK8Udmm.bFU3c2Tt6',
     firstName: 'test',
     lastName: 'ing',
     createdAt: 2019-02-26T15:47:09.133Z,
     updatedAt: 2019-02-26T15:47:09.133Z },
  _changed: {},
  _modelOptions:
   { timestamps: true,
     validate: {},
     freezeTableName: false,
     underscored: false,
     underscoredAll: false,
     paranoid: false,
     rejectOnEmpty: false,
     whereCollection: { email: 'testing@gmail.com' },
     schema: null,
     schemaDelimiter: '',
     defaultScope: {},
     scopes: [],
     indexes: [],
     name: { plural: 'Users', singular: 'User' },
     omitNull: false,
     hooks:
      { beforeCreate: [Array],
        beforeUpdate: [Array],
        beforeSave: [Array] },
     sequelize:
      Sequelize {
        options: [Object],
        config: [Object],
        dialect: [SqliteDialect],
        queryInterface: [QueryInterface],
        models: [Object],
        modelManager: [ModelManager],
        connectionManager: [ConnectionManager],
        importCache: [Object],
        test: [Object] },
     uniqueKeys: { Users_email_unique: [Object] } },
  _options:
   { isNewRecord: false,
     _schema: null,
     _schemaDelimiter: '',
     raw: true,
     attributes:
      [ 'id',
        'username',
        'email',
        'password',
        'firstName',
        'lastName',
        'createdAt',
        'updatedAt' ] },
  __eagerlyLoadedAssociations: [],
  isNewRecord: false }

console.log(req.body) 给了我这个:

{ email: 'testing@gmail.com',
  password: 'testing99',
  username: 'testing',
  firstName: 'test',
  lastName: 'ing' }

他们有相同的信息,但无论如何它给了我一个错误。

标签: node.jsexpresssequelize.js

解决方案


我们这里有两个解决方案:

  1. 使用原始:真

    const user = await User.findOne({ where: { email: email }, raw: true })

  2. 使用普通:真

    user = user.get({plain: true });


推荐阅读