繁体   English   中英

注册不工作并抛出参数错误

[英]Sign Up not working and throwing params errors

我目前可以使用之前创建的用户凭据正常登录并正常使用该应用程序,但无法创建新用户。 我在客户端使用 React.js,在后端使用 Express api。 我收到猫鼬验证错误。 所有身份验证都随课程使用的模板一起提供,我没有接触过任何这些文件。 我什至回去比较提交历史树以确保没有任何更改。

这是我的用户架构和注册路线。 我尝试从模型中消除唯一性,但这并没有影响它。 我知道有很多潜在的地方可能会出错,但是如果有人对潜在问题有任何建议,我将永远感激不尽! 我在注册时控制台记录了 req.body.credentials,发送的数据看起来不错。

错误代码:422 无法处理的实体服务器端错误:“收到的参数未能通过猫鼬验证”

const mongoose = require('mongoose')
const { petSchema } = require('./pet.js')
const { pictureSchema } = require('./picture.js')

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true
  },
  hashedPassword: {
    type: String,
    required: true
  },
  token: String,
  pets: [petSchema],
  pictures: [pictureSchema]
}, {
  timestamps: true,
  toObject: {
    // remove `hashedPassword` field when we call `.toObject`
    transform: (_doc, user) => {
      delete user.hashedPassword
      return user
    }
  }
})

module.exports = mongoose.model('User', userSchema)
// SIGN UP
// POST /sign-up
router.post('/sign-up', (req, res) => {
  // start a promise chain, so that any errors will pass to `handle`
  console.log(req.body.credentials)
  Promise.resolve(req.body.credentials)
    // reject any requests where `credentials.password` is not present, or where
    // the password is an empty string
    .then(credentials => {
      if (!credentials ||
          !credentials.password ||
          credentials.password !== credentials.password_confirmation) {
        throw new BadParamsError()
      }
    })
    // generate a hash from the provided password, returning a promise
    .then(() => bcrypt.hash(req.body.credentials.password, bcryptSaltRounds))
    .then(hash => {
      // return necessary params to create a user
      return {
        email: req.body.credentials.email,
        hashedPassword: hash
      }
    })
    // create user with provided email and hashed password
    .then(user => User.create(user))
    // send the new user object back with status 201, but `hashedPassword`
    // won't be sent because of the `transform` in the User model
    .then(user => res.status(201).json({ user: user.toObject() }))
    // pass any errors along to the error handler
    .catch(err => handle(err, res))
})

解决了。 我在 user 中拥有的子文档之一有一个键,其值设置为唯一。 我需要消除它,因为我的数据库正在使用空值索引用户并抛出重复错误。 然后我需要重置我的数据库(我只是重命名它以测试它),以便它没有任何保存的具有该配置的索引。 我也刚刚在 Heroku 中删除了我的集合(幸运的是我那里没有大量数据,这个解决方案非常适合我的情况)。 我现在可以再次注册用户,而不会出现任何重复的密钥错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM