'Facing this error while implementing this forgot password route or sending post request through postman
Here are the screenshots and code attached Code:
exports.forgotPassword = async function(req, res, next) {
//Check if user exists
const user = await User.findOne({ email: req.body.email })
if (!user) {
return next(new AppError('There is no user with this email address', 404))
}
//Generate the random reset token
const resetToken = user.createPasswordResetToken()
await user.save({ validateBeforeSave: false });
//send it to user's mail
const resetURL = `${req.protocol}://${req.get('host')}/api/users/resetPassword/${resetToken}`;
const message = `Forgot your Password? Submit a patch request with your password and confirm password to ${resetURL}`
try {
await sendEmail({
email: user.email,
subject: 'Your password reset token(valid for 10 min)'
})
res.status(200).json({
status: 'success',
message: 'Token sent to Email'
})
} catch (err) {
user.passwordResetToken = undefined;
user.passwordResetExpires = undefined;
await user.save({ validateBeforeSave: false });
return next(new AppError('There was an error sending the email. Please try again later!'), 500);
}
}
Error Message :
Error: There was an error sending the email. Please try again later!
at exports.forgotPassword (D:\FYP\controllers\authController.js:94:22)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Error: getaddrinfo ENOTFOUND smtp.mailtrap.io;
at GetAddrInfoReqWrap.onlookup [as oncomplete]
(node:dns:71:26) {
errno: -3008,
code: 'EDNS',
syscall: 'getaddrinfo',
hostname: 'smtp.mailtrap.io;',
command: 'CONN'
}
Solution 1:[1]
look at my code it used express.js with typescript use ndoemailer to send email
public async forgot(entity: AuthEntity): Promise<void> {
if (isEmpty(entity)) throw new HttpException(StatusCodes.BAD_REQUEST, i18n.t("api.commons.reject"));
let findUser: IUser;
if (entity.email !== undefined) {
findUser = await this.userModel.findOne({ email: entity.email });
if (!findUser) {
// @ts-ignore
await ipActivityModel.storeIp(false, "forgot", entity);
throw new HttpException(StatusCodes.CONFLICT, i18n.t("auth.youAreNotEmail"));
}
await this.sendForgotEmail(findUser.email, entity.resetToken);
}
}
public async sendForgotEmail(email: string, hash: string): Promise<void> {
const transporter = nodemailer.createTransport({
host: config.get("email.host"),
port: config.get("email.port"),
secure: config.get("email.secure"), // true for 465, false for other ports
auth: config.get("email.auth")
});
const mailContext = {
siteAddress: config.get("siteAddress"),
emailForgotTitle: i18n.t("auth.emailForgotTitle"),
emailForgotGuide: i18n.t("auth.emailForgotGuide"),
emailActivateHash: i18n.t("auth.emailActivateHash"),
hash: hash,
emailForgotVisit: i18n.t("auth.emailForgotVisit"),
emailActivateIgnore: i18n.t("auth.emailActivateIgnore"),
emailForgotResetFrom: i18n.t("auth.emailForgotResetFrom")
};
const template = await ejs.renderFile("./dist/modules/auth/views/forgot.html", mailContext);
const mailOptions = {
from: config.get("email.fromEmail"),
to: email,
subject: config.get("siteAddress") + " (" + i18n.t("api.events.emailForgot") + ")",
html: template
};
let isSend = await transporter.sendMail(mailOptions);
if (!isSend.messageId) {
throw new HttpException(StatusCodes.CONFLICT, i18n.t("auth.emailSendErrorForgot"));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
