Не удается сохранить и активировать зарегистрированную учетную запись электронной почты

#node.js #api #express #sendgrid

#node.js #API #экспресс #sendgrid

Вопрос:

Я успешно отправил токен по электронной почте при регистрации через сетку отправки

 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,
            firstname,
            email,
            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, accountActivation, (err) => {
        if (err) {
            console.log('Activation error');
            return res.status(401).json({
                errors: 'Expired link. Signup again',
            });
        } else {
            const { lastname, firstname, email, password } = jwt.decode(
                token
            );

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

            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',
    });
}});
  

Я всегда получаю эту ошибку.

Ошибка

Я даже пытался делать

  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,
    required: true,
},
email: {
    type: String,
    required: true,
    unique: true,
},
password: {
    type: String,
    required: true,
},
avatar: {
    type: String,
},
date: {
    type: Date,
    default: Date.now,
},}); module.exports = Use = mongoose.model('user', UserSchema);
  

ошибка моего почтальона:

Почтальон

Ответ №1:

Мне удается выяснить проблему. Это потому, что я создал двойной экземпляр пользователя

поэтому я удалил экземпляр пользователя из регистрации

 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,
                firstname,
                email,

                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');
    }
});
  

и поместите его в активацию учетной записи вместе с gravatar и хешированием паролей

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

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

        const { lastname, firstname, email, 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,
            firstname,
            email,
            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);

        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',
    });
}});
  

и это успешно, пользователь сохраняется в базе данных.

Успешно сохранено