Node.js Email Verification API: Send Email with Code and Prevent Frequent Requests
Node.js Email Verification API: Send Email with Code and Prevent Frequent Requests
This code snippet demonstrates a Node.js API endpoint that handles email verification by sending a unique code to the user's email address. It also implements a basic rate limiting feature to prevent excessive requests within a short period.
API Endpoint (exports.email):
exports.email = (req, res) => {
// 查询邮箱是否被占用
const userinfo = req.body;
const sqlStr = `SELECT * FROM userinfo WHERE email = ?`;
db.query(sqlStr, userinfo.email, (err, results) => {
if (err) {
return res.cc(err)
}
// 判断用户名是否被占用
if (results.length > 0) {
return res.cc('邮箱已被占用,请更换!');
}
// 生成四位随机数
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var code = '';
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
for (var i = 1; i <= 4; i++) {
var txt = str[randomNum(0, str.length)];
code = code + txt;
}
// 发送邮箱验证码
let transporter = nodemailer.createTransport({
host: 'smtp.163.com',
port: 465, // SMTP 端口
auth: { //发送者的账户和授权码
user: '15576730892@163.com', //账户
pass: 'LRTYRUNEMKHWLVZS', //smtp授权码,到邮箱设置下获取
}
});
let mailOptions = {
from: '15576730892@163.com', // 发送者昵称和地址
to: userinfo.email, // 接收者的邮箱地址
subject: '验证码', // 邮件主题
html: code + '
次元人欢迎您的到来!'
};
//发送邮件
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
res.write('邮件发送成功 ID:', info.messageId);
});
res.send({
status: 0,
message: '验证码发送成功!',
results: code
});
})
}
// Rate Limiting Logic (Prevent Frequent Requests)
let lastRequestTime = 0;
exports.email = (req, res) => {
// 计算距离上次请求的时间间隔
const currentTime = Date.now();
const interval = currentTime - lastRequestTime;
// 判断距离上次请求是否超过60秒
if (interval < 60000) {
return res.cc('每隔60秒允许发送第二次请求,请稍后再试!');
}
// 更新上次请求时间
lastRequestTime = currentTime;
// 其他逻辑代码... (The original email sending logic goes here)
}
Explanation:
- Email Verification: The API checks if the provided email is already registered. If not, it generates a 4-digit random code and sends it to the user's email using Nodemailer. The code is included in the email body for user verification.
- Rate Limiting: To prevent excessive requests, the code implements a simple rate limiting mechanism. It uses the
lastRequestTimevariable to track the timestamp of the last request. If a new request comes within 60 seconds of the previous one, it returns an error message indicating the user should wait. Otherwise, it updates thelastRequestTimeand proceeds with the email sending logic.
Note:
- Replace the placeholders (e.g., email credentials, database connection) with your actual values.
- This is a basic implementation. For production environments, you may consider more robust rate limiting solutions and database interaction practices.
- This code assumes you have Nodemailer and your database library installed and configured.
AI 优化版
原文地址:https://www.cveoy.top/t/topic/qh07 著作权归作者所有。请勿转载和采集!