Я реализую функцию сброса пароля в своем приложении на основе этого учебника: https://itnext.io/password-reset-emails-in-your-react-app-made-easy-with-nodemailer-bb27968310d7?gi=574338d418a9
В форме сброса пароля при отправке электронного письма я получаю письмо для сброса пароля с express и может сбросить пароль с помощью токена:
Executing (default): SELECT "id", "username", "email", "usertype", "password_digest", "avatar", "reset_password_token" AS "resetPasswordToken", "reset_password_expires" AS "resetPasswordExpires", "created_at" AS "createdAt", "updated_at" AS "updatedAt" FROM "users" AS "user" WHERE "user"."email" = 'me@gmail.com';
Executing (default): UPDATE "users" SET "reset_password_token"=$1,"reset_password_expires"=$2,"updated_at"=$3 WHERE "id" = $4
Message sent: undefined f68a6a6d5e8892f9b0b24ef13ebeda4e2b2b40ff
Однако после отправки пароля вышеприведенное сообщение сервера зависает до тех пор, пока я не остановлюсь express, и в этот момент мне представляется это ошибка в React.
Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
ForgotPassword.sendEmail
src/editModules/View/ForgotPassword.jsx:58
ForgotPassword.jsx (React)
class ForgotPassword extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
showError: false,
messageFromServer: "",
showNullError: false
};
}
handleChange = name => event => {
this.setState({
[name]: event.target.value
});
};
sendEmail = async e => {
e.preventDefault();
const { email } = this.state;
if (email === "") {
this.setState({
showError: false,
messageFromServer: "",
showNullError: true
});
} else {
try {
const response = await axios.post(
"http://localhost:4000/forgot/",
{
email,
});
console.log(response.data);
if (response.data === "recovery email sent") {
this.setState({
showError: false,
messageFromServer: "recovery email sent",
showNullError: false
});
// this.props.history.push("/checkmail");
}
} catch (error) {
console.error(error.response.data);
if (error.response.data === "email not in db") {
this.setState({
showError: true,
messageFromServer: "",
showNullError: false
});
}
}
}
};
render() {
const { email, messageFromServer, showNullError, showError } = this.state;
return (
<>
<Header />
<div id="page-container">
<div id="auth-container">
<h1 className="center-it">Forgot Password</h1>
<form onSubmit={this.sendEmail}>
<input
className="input"
id="email"
label="email"
style={{width: '100%'}}
value={email}
onChange={this.handleChange("email")}
placeholder="Email Address"
/>
<br />
<br />
<button className="auth-button">
Send Password Reset Email
</button>
</form>
{showNullError && (
<div>
<p id="alert">The email address field is empty.</p>
</div>
)}
{showError && (
<div>
<p id="alert">
That email address isn't recognized. Please try again
or register for a new account.
</p>
</div>
)}
{messageFromServer === "recovery email sent" && (
<div>
<p id="alert">Password Reset Email Successfully Sent!</p>
</div>
)}
</div>
</div>
<Footer />
</>
);
}
}
export default withRouter(ForgotPassword);
ForgotPassword. js (Express)
pwRouter.post('/forgot', async (req, res) => {
if (req.body.email === '') {
res.status(400).send('email required');
}
console.error(req.body.email);
User.findOne({
where: {
email: req.body.email,
},
}).then((user) => {
if (user === null) {
console.error('email not in database');
res.status(403).send('email not in db');
} else {
const token = crypto.randomBytes(20).toString('hex');
user.update({
resetPasswordToken: token,
resetPasswordExpires: Date.now() + 360000,
});
const options = {
auth: {
api_user: process.env.UN,
api_key: process.env.PW
}
};
const client = nodemailer.createTransport(sgTransport(options));
const email = {
from: 'support@gmail.com',
to: `${user.email}`,
subject: 'Password Reset Link',
text:
'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n'
+ 'Please click on the following link, or paste this into your browser to complete the process within one hour of receiving it:\n\n'
+ `http://localhost:3000/reset/${token}\n\n`
+ 'If you did not request this, please ignore this email and your password will remain unchanged.\n',
};
client.sendMail(email, function(err, info){
if (err ){
console.log(err);
}
else {
console.log('Message sent: ' + info.response, token);
}
});
}
});
});
module.exports = {
pwRouter,
};
I'm застрял на этом этапе, так как все другие функции аутентификации в приложении работают правильно. Я прошел репо, это основано на том, что я не могу точно понять, где я ошибся.