繁体   English   中英

RangeError:nodejs 和 reactjs 中超出了最大调用堆栈大小

[英]RangeError: Maximum call stack size exceeded in nodejs and reactjs

我尝试通过下面的代码发布从我的注册中获得的令牌,但出现错误,超出了最大调用堆栈

exports.activationController = (req, res) => {
  const { token } = req.body;

  exports.activationController = (req, res) => {
  const { token } = req.body;

  if (token) {
    jwt.verify(token, process.env.JWT_ACCOUNT_ACTIVATION, (err, decoded) => {
      if (err) {
        return res.status(401).json({
          errors: 'Expired link. Signup again'
        });
      } else {
        const { name, email, password } = jwt.decode(token);

        const user = new User({
          name,
          email,
          password
        });

        user.save((err, user) => {
          if (err) {
            return res.status(401).json({
              errors: 'User cannot be saved.'
            });
          } else {
            return res.json({
              success: true,
              message: 'Signup success'
            });
          }
        });
      } 
    });
  } else {
    return res.json({
      message: 'Please try again.'
    });
  }
};

我已经完成了这样的注册

exports.registerController = (req, res) => {
    const { name, email, password } = req.body;
    const errors = validationResult(req);
    

    if (!errors.isEmpty()) {
      const firstError = errors.array().map(error => error.msg)[0];
      return res.status(422).json({
        errors: firstError
      });
    } else {
      User.findOne({
        email
      }).exec((err, user) => {
        if (user) {
          return res.status(400).json({
            errors: 'Email is taken'
          });
        }
      });

      const token = jwt.sign(
        {
          name,
          email,
          password
        },
        process.env.JWT_ACCOUNT_ACTIVATION,
        {
          expiresIn: '5m'
        }
      );

      const emailData = {
        from: process.env.EMAIL_FROM,
        to: email,
        subject: 'Account activation link',
        html: `
                  <h1>Please use the following to activate your account</h1>
                  <button style="padding: 15px; background-color: blue; text-align:center; opacity: 0.2; outline: none; border-radius: 10px;"><a style="text-decoration: none; color: white;" href="${process.env.CLIENT_URL}/users/activate/${token}">Activate your account</a></button>
                  <hr />
                  <p>This email may containe sensetive information</p>
                  <p>${process.env.CLIENT_URL}</p>
              `
      };

使用邮递员发布激活时,我收到错误“超出最大调用堆栈”。我真的不知道我的代码在哪里,这个错误来自

这是回应

RangeError:超出最大调用堆栈大小
在 RegExp.test (<匿名>)
在 _pathToPositionalSyntax (C:\\Users\\User\\Documents\\My projects\\greenlifeapp\\node_modules\\mongoose\\lib\\schema.js:854:16)
在 Schema.pathType (C:\\Users\\User\\Documents\\My projects\\greenlifeapp\\node_modules\\mongoose\\lib\\schema.js:1200:21)
在model.$set (C:\\Users\\User\\Documents\\My projects\\greenlifeapp\\node_modules\\mongoose\\lib\\document.js:1160:33)
在 model.set [作为密码] (C:\\Users\\User\\Documents\\My projects\\greenlifeapp\\node_modules\\mongoose\\lib\\helpers\\document\\compile.js:174:19)
在模型。<匿名> (C:\\Users\\User\\Documents\\My projects\\greenlifeapp\\models\\auth.model.js:34:19)
在 VirtualType.applySetters (C:\\Users\\User\\Documents\\My projects\\greenlifeapp\\node_modules\\mongoose\\lib\\virtualtype.js:167:16)
在model.$set (C:\\Users\\User\\Documents\\My projects\\greenlifeapp\\node_modules\\mongoose\\lib\\document.js:1264:12)
在 model.set [作为密码] (C:\\Users\\User\\Documents\\My projects\\greenlifeapp\\node_modules\\mongoose\\lib\\helpers\\document\\compile.js:174:19)
在模型。<匿名> (C:\\Users\\User\\Documents\\My projects\\greenlifeapp\\models\\auth.model.js:34:19)

我定义用户的猫鼬模型

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        trim: true,
        required: true,
        unique: true,
        lowercase: true
    }, 
    name: {
        type: String,
        trim: true,
        required: true     
    }, 
    hashed_password: {
        type: String,
        required: true
    },
    salt: String,
    role: {
        type: String,
        default: 'Normal'
    },
    resetPasswordLink: {
        data: String,
        default: ''
    }
}, {timeStamp: true})

// Virtual password
userSchema.virtual('password')
.set(function(password){
    this.password = password
    this.salt = this.makeSalt()
    this.hashed_password = this.encryptPassword(password)
})
.get(function(){
    return this._password
})

// Methods
userSchema.methods = {
    // Generate salt
    makeSalt: function(){
        return Math.round(new Date().valueOf() * Math.random()) + ''
    },
    // Encrypt Password
    encryptPassword: function(password){
        if(!password) return ''
        try{
            return crypto
            .createHmac('sha1', this.salt)
            .update(password)
            .digest('hex')
        } catch (err) {
            return ''
        }
    },
    authenticate: function (plainPassword) {
        return this.encryptPassword(plainPassword) === this.hashed_password
    }
}

module.exports = mongoose.model('User', userSchema)

所有与数据库相关的操作(如 find、save、findOne)本质上都是异步的。 要执行它,您应该使用 promise 或 async/await。 例如。 要保存用户,您应该使用它

exports.activationController = async (req, res) => {
  const { token } = req.body;

  if (token) {
    jwt.verify(token, process.env.JWT_ACCOUNT_ACTIVATION, (err, decoded) => {
      if (err) {
        return res.status(401).json({
          errors: 'Expired link. Signup again'
        });
      } else {
        const { name, email, password } = jwt.decode(token);

        const user = new User({
          name,
          email,
          password
        });

        await user.save((err, user) => {
          if (err) {
            return res.status(401).json({
              errors: 'User cannot be saved.'
            });
          } else {
            return res.json({
              success: true,
              message: 'Signup success'
            });
          }
        });
      } 
    });
  } else {
    return res.json({
      message: 'Please try again.'
    });
  }
};

并像这样注册

exports.registerController = async (req, res) => {
    const { name, email, password } = req.body;
   // if validationResult is async function use await here as well
    const errors = validationResult(req);
    

    if (!errors.isEmpty()) {
      const firstError = errors.array().map(error => error.msg)[0];
      return res.status(422).json({
        errors: firstError
      });
    } else {
      await User.findOne({
        email
      }).exec((err, user) => {
        if (user) {
          return res.status(400).json({
            errors: 'Email is taken'
          });
        }
      });

      const token = jwt.sign(
        {
          name,
          email,
          password
        },
        process.env.JWT_ACCOUNT_ACTIVATION,
        {
          expiresIn: '5m'
        }
      );

      const emailData = {
        from: process.env.EMAIL_FROM,
        to: email,
        subject: 'Account activation link',
        html: `
                  <h1>Please use the following to activate your account</h1>
                  <button style="padding: 15px; background-color: blue; text-align:center; opacity: 0.2; outline: none; border-radius: 10px;"><a style="text-decoration: none; color: white;" href="${process.env.CLIENT_URL}/users/activate/${token}">Activate your account</a></button>
                  <hr />
                  <p>This email may containe sensetive information</p>
                  <p>${process.env.CLIENT_URL}</p>
              `
      };

让我知道它是否有帮助。

暂无
暂无

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

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