无法保存和激活注册的电子邮件帐户

问题描述

在通过“发送表格”注册后,我已经成功在电子邮件中发送了令牌

router.post(
'/',[
    check('lastname','Lastname is required').not().isEmpty(),check('firstname','Firstname is required').not().isEmpty(),check('email','Please include a valid email').isEmail(),check(
        'password','Please enter a password with 6 or more characters'
    ).isLength({ min: 6 }),],async (req,res) => {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }

    const { lastname,firstname,email,password } = req.body;

    try {
        // Identify if users exists
        let user = await User.findOne({ email });

        if (user) {
            return res.status(400).json({
                errors: [{ msg: 'User already exists' }],});
        }

        // Get users avatar
        const avatar = gravatar.url(email,{
            // size
            s: '200',// rating
            r: 'pg',// default (mm = default image)
            d: 'mm',});

        // create a new instance of a user
        user = new User({
            lastname,avatar,password,});

        // // Encrypt password

        // // salt to do the hashing
        const salt = await bcrypt.genSalt(10);

        // // creates a hash and put to the user.password
        user.password = await bcrypt.hash(password,salt);

        const token = jwt.sign(
            {
                user,},accountActivation,{
                expiresIn: 360000,}
        );

        const emailData = {
            from: emailFrom,to: user.email,subject: 'Account Activation',html: `
                <h1>Please use the following to activate your account</h1>
                <p>${PORT}/activeprofile/${token}</p>
                <hr />
                <p>This email may contain sensetive information</p>
                <p>${PORT}</p>
            `,};

        sgMail
            .send(emailData)
            .then(() => {
                return res.json({
                    message: `Email has been sent to ${email}`,});
            })
            .catch((err) => {
                return res.status(400).json({
                    msg: 'Unable to send',});
            });
        // await user.save()
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server error');
    }
});

我已经成功收到一封带有令牌的电子邮件

无论何时我想在邮递员中进行验证。

router.post('/activeprofile',(req,res) => {
const { token } = req.body;

if (token) {
    jwt.verify(token,(err) => {
        if (err) {
            console.log('Activation error');
            return res.status(401).json({
                errors: 'Expired link. Signup again',});
        } else {
            const { lastname,password } = jwt.decode(
                token
            );

            // create a new instance of a user
            const user = new User({
                lastname: req.body.lastname,});

            user.save((err,user) => {
                if (err) {
                    console.log('Error Saving the User',err.message);
                    return res.status(401).json({ msg: 'Unable to save' });
                } else {
                    return res.status(200).json({
                        success: true,message: user,message: 'Signup Success',});
                }
            });
        }
    });
} else {
    return res.json({
        message: 'Error happened,Please try again later',});
}});

我总是会收到此错误

Error

我什至尝试做

 const user = new User({
                lastname: req.body.lastname,firstname: req.body.firstname,email: req.body.email,password: req.body.passsword,});

我仍然在发布的图片中遇到了所有相同的错误

顺便说一句。这是我的用户架构

const UserSchema = new mongoose.Schema({
lastname: {
    type: String,required: true,firstname: {
    type: String,email: {
    type: String,unique: true,password: {
    type: String,avatar: {
    type: String,date: {
    type: Date,default: Date.Now,}); module.exports = Use = mongoose.model('user',UserSchema);

我的邮递员错误

Postman

解决方法

我设法找出问题所在。这是因为我创建了用户的双重实例

所以我从注册中删除了用户实例

router.post(
'/',[
    check('lastname','Lastname is required').not().isEmpty(),check('firstname','Firstname is required').not().isEmpty(),check('email','Please include a valid email').isEmail(),check(
        'password','Please enter a password with 6 or more characters'
    ).isLength({ min: 6 }),],async (req,res) => {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }

    const { lastname,firstname,email,password } = req.body;

    try {
        // Identify if users exists
        let data = await User.findOne({ email });

        if (data) {
            return res.status(400).json({
                errors: [{ msg: 'User already exists' }],});
        }

        const token = jwt.sign(
            {
                lastname,password,},accountActivation,{
                expiresIn: 360000,}
        );

        const emailData = {
            from: emailFrom,to: email,subject: 'Account Activation',html: `
                <h1>Please use the following to activate your account</h1>
                <p>${PORT}/activeprofile/${token}</p>
                <hr />
                <p>This email may contain sensetive information</p>
                <p>${PORT}</p>
            `,};

        sgMail
            .send(emailData)
            .then(() => {
                return res.json({
                    message: `Email has been sent to ${email}`,});
            })
            .catch((err) => {
                return res.status(400).json({
                    msg: 'Unable to send',});
            });
        // await user.save()
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server error');
    }
});

并将其与密码和密码哈希一起用于帐户激活

router.post('/activeprofile',(req,res) => {
const { token } = req.body;

if (token) {
    jwt.verify(token,async (err,decoded) => {
        if (err) {
            console.log('Activation error');
            return res.status(401).json({
                errors: 'Expired link. Signup again',});
        }

        const { lastname,password } = jwt.decode(token);

        // // Get users avatar
        const avatar = gravatar.url(email,{
            // size
            s: '200',// rating
            r: 'pg',// default (mm = default image)
            d: 'mm',});

        // create a new instance of a user
        let user = new User({
            lastname,avatar,});

        // Encrypt password

        // salt to do the hashing
        const salt = await bcrypt.genSalt(10);

        // creates a hash and put to the user.password
        user.password = await bcrypt.hash(password,salt);

        user.save((err,user) => {
            if (err) {
                console.log('Error Saving the User',err.message);
                return res.status(401).json({ msg: 'Unable to save' });
            } else {
                return res.status(200).json({
                    success: true,message: user,message: 'Signup Success',});
            }
        });
    });
} else {
    return res.json({
        message: 'Error happened,Please try again later',});
}});

成功,用户被保存在数据库中。

Successfully Saved