简体   繁体   English

如何解决nodejs中的“未定义”错误

[英]how to solve a 'res is not defined' error in nodejs

I am trying to get test the controller logic for a user validation module but I keep on landing res is not defined error even after trying to define it.我正在尝试为用户验证模块测试 controller 逻辑,但即使在尝试定义它之后,我仍会继续登陆 res is not defined 错误。 How I'm I supposed properly define it so that it is able to correctly run through the condition statements correctly?我应该如何正确定义它,以便它能够正确运行条件语句?

my common.js validation logic我的 common.js 验证逻辑

const user = require('../models/user');

module.exports = {
    verifyEmail: async(email) => {
        if (!email) {
            return res.status(404).json({ message: 'Email is required' })
        }
        let regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        if (!email.match(regex)) {
            return res.status(400).json({ message :'invalid email address' })
        }
        let User = await user.findOne({ email });
        if (User) {
            return res.status(400).json({ message: 'User already exists' })
        }

    },
    verifyFirstName: (firstName) => {
        if (!firstName) {
            return res.status(404).json({ message: 'First name is required' });
        }
        if (firstName.length < 3 || firstName.length > 20) {
            return res.status(411).json({ message: 'length must be between 3 and 20 characters' });
        }
    },
    verifyLastName: (lastName) => {
        if (!lastName) {
            return res.status(404).json({ message: 'First name is required' });
        }
        if (lastName.length < 3 || lastName.length > 20) {
            return res.status(411).json({ message: 'length must be between 3 and 20 characters' });
        }
    },
    verifyPassword: (password, confirmPassword) => {
        if (!password) {
            return res.status(404).json({ message: 'Password field is required' })
        }
        if (password.length < 5) {
            return res.status(411).json({ message: 'Password is too short' })
        }
        let passRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{5,15}$/;
        if (!password.match(passRegex)) {
            return res.status(400).json({ message: 'Password must include at least one lowercase letter, one uppercase letter, one digit, and one special character' });
        }
        if (password !== confirmPassword) {
            return res.status(417).json({ message: 'passwords do not match' })
        }
    },
    verifyPhone: (phoneNumber) => {
        if (!phoneNumber) {
            return res.status(404).json({ message: 'Phone number is required' })
        }
        let phoneRegex = /^\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}$/
        if (!phoneNumber.match(phoneRegex)) {
            return res.status(400).json({ message: 'Please add a valid phone number' })
        }
    }

}

controller.js controller.js

module.exports.users = async(req, res) => {
    try {
        const { email, firstName, lastName, password, confirmPassword, phoneNumber } = req.body

        verifier.verifyEmail(email);
        verifier.verifyFirstName(firstName);
        verifier.verifyLastName(lastName);
        verifier.verifyPassword(password, confirmPassword);
        verifier.phoneNumber(phoneNumber);


        let User = new user({
            firstName: req.body.firstName,
            lastName: req.body.lastName,
            password: req.body.password,
            phone: req.body.phoneNumber

        })

        bcrypt.genSalt(10, async(err, salt) => {
            if (err) throw err;
            return user.password = await bcrypt.hash(user.password, salt);
        });
        await User.save();

res doesn't seem to be defined in your validation logic. res 似乎没有在您的验证逻辑中定义。 You can try returning the status and message to your controller instead.您可以尝试将状态和消息返回给您的 controller。

eg例如

    verifyEmail: async(email) => {
        if (!email) {
            return { status: 404, message: 'Email is required' };
        }
        ...
    },

then in your controller,然后在您的 controller 中,

let emailValidation = verifier.verifyEmail(email);
if (emailValidation.status === 404 || emailValidation.status === 400) {
    res.status(emailValidation.status).json({ message: emailValidation.message });
}

Rather than using custom validation, I will recommend you use the Joi package for validation.我建议您使用Joi package 进行验证,而不是使用自定义验证。 So your end file will look like this.所以你的最终文件看起来像这样。

Joi Package乔伊 Package

validation.js验证.js

const Joi = require('joi')

const validateSchema = (body, schema) => {
  try {
    const { error } = schema.validate(body)
    return { error }
  } catch (err) {
    throw err
  }
}

exports.userValidator = (body) => {
  const schema = Joi.object({
    email: Joi.string().email({ minDomainSegments: 2 }).required(),
    firstName: Joi.string().min(3).max(20),
    lastName: Joi.string().min(3).max(20),
    password: Joi.string().required(),
    phoneNumber: Joi.string()
      .length(10)
      .pattern(/^[0-9]+$/)
      .required()
  })

  return validateSchema(body, schema)
}

controller.js controller.js

 module.exports.user = async (req, res, next) => {
  try {
    // const { email, firstName, lastName, password, phoneNumber } = req.body

    const { error } = userValidator(req.body)
    if (error) return res.status(400).json({ message: 'Error occured!', error })

    let user = await User.findOne({ email: req.body.email })
    if (user) {
      return res.status(400).json({ message: 'User already exists' })
    }

    bcrypt.genSalt(10, async (err, salt) => {
      if (err) throw err
      req.body.password = await bcrypt.hash(user.password, salt)
    })

    user = new User(req.body)

    await user.save()
  } catch (err) {
    console.log(err)
  }
}

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

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