📅  最后修改于: 2023-12-03 15:09:54.114000             🧑  作者: Mango
在 Web 应用程序中,经常有用户忘记他们的密码的情况。本文将向您展示如何使用 Node.js 和 MongoDB 构建忘记密码的 API。
mkdir forgot-password-api
cd forgot-password-api
npm init -y
mongoose
,解决跨域的 cors
和发送电子邮件的 nodemailer
。 npm i mongoose cors nodemailer
app.js
文件中添加以下代码: const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())
/forgot-password
。 const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/forgot-password-db')
const UserSchema = new mongoose.Schema({
name: String,
email: String,
password: String
})
const User = mongoose.model('User', UserSchema)
app.post('/forgot-password', async (req, res) => {
const { email } = req.body
const user = await User.findOne({ email })
if (!user) {
res.status(404).send('User not found')
return
}
})
const ResetPasswordSchema = new mongoose.Schema({
email: String,
token: String,
createdAt: {
type: Date,
default: Date.now,
expires: 3600 // Expire after 1 hour
}
})
const ResetPassword = mongoose.model('ResetPassword', ResetPasswordSchema)
app.post('/forgot-password', async (req, res) => {
// Check if user exists
const { email } = req.body
const user = await User.findOne({ email })
if (!user) {
res.status(404).send('User not found')
return
}
// Create reset password record
const token = crypto.randomBytes(20).toString('hex')
const resetPassword = new ResetPassword({
email: user.email,
token
})
await resetPassword.save()
// Send email to user
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
auth: {
user: 'your_email@gmail.com',
pass: 'your_password'
}
})
const mailOptions = {
to: user.email,
from: 'your_email@gmail.com',
subject: 'Reset your password',
text: `Hi, ${user.name}!\n\nYou are receiving this email because you requested a password reset for your account. Please click on the link below to reset your password:\n\nhttp://localhost:3000/reset-password/${token}\n\nIf you did not request this, please ignore this email and your password will remain unchanged.\n`
}
transporter.sendMail(mailOptions, err => {
if (err) {
console.log(err)
res.status(500).send('Error sending email')
return
}
res.send('Email sent')
})
})
POST /reset-password
,该路由将检查令牌是否有效并使用新密码更新数据库中的用户密码。 app.post('/reset-password', async (req, res) => {
const { token, password } = req.body
const resetPassword = await ResetPassword.findOne({ token })
if (!resetPassword) {
res.status(404).send('Invalid or expired token')
return
}
const user = await User.findOne({ email: resetPassword.email })
if (!user) {
res.status(404).send('User not found')
return
}
await user.updateOne({ password })
await resetPassword.deleteOne()
res.send('Password updated')
})
node app.js
恭喜,您已经学会了如何使用 Node.js 和 MongoDB 创建忘记密码的 API!这是 Web 应用程序中非常有用的功能,因为用户可能会经常忘记密码。