在Web应用开发中,用户注册和身份验证是常见的功能之一。为了提高安全性和验证用户的有效性,通常会使用邮箱验证码。本文将介绍如何使用Node.js发送邮箱验证码,以增强用户注册流程的安全性。
准备工作
首先,确保你已经安装了Node.js和npm。然后,创建一个新的Node.js项目,并在项目目录中运行以下命令安装所需的依赖:
npm init -y
npm install nodemailer express body-parser
这将安装用于发送邮件的nodemailer
库,以及用于创建Web服务器和处理请求的express
和body-parser
库。
编写代码
创建一个名为app.js
的文件,并使用以下代码初始化你的应用:
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const app = express();
const port = 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// 设置nodemailer配置
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your_email@gmail.com',
pass: 'your_email_password'
}
});
// 生成随机验证码
function generateOTP() {
return Math.floor(100000 + Math.random() * 900000).toString();
}
// 存储验证码和邮箱对应关系
const otpMap = new Map();
// 处理发送验证码请求
app.post('/send-otp', (req, res) => {
const { email } = req.body;
if (!email) {
return res.status(400).json({ error: 'Invalid email address' });
}
const otp = generateOTP();
otpMap.set(email, otp);
const mailOptions = {
from: 'your_email@gmail.com',
to: email,
subject: 'Verification Code',
text: `Your verification code is: ${otp}`
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return res.status(500).json({ error: 'Error sending verification code' });
}
res.status(200).json({ message: 'Verification code sent successfully' });
});
});
// 处理验证验证码请求
app.post('/verify-otp', (req, res) => {
const { email, otp } = req.body;
if (!email || !otp) {
return res.status(400).json({ error: 'Invalid email or verification code' });
}
const storedOTP = otpMap.get(email);
if (storedOTP && storedOTP === otp) {
otpMap.delete(email);
return res.status(200).json({ message: 'Verification successful' });
} else {
return res.status(401).json({ error: 'Invalid verification code' });
}
});
// 启动服务器
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
请替换代码中的your_email@gmail.com
和your_email_password
为你的发件人邮箱和密码。
测试
使用Postman或其他工具发送POST请求进行测试。首先,发送一个请求以获取验证码:
{
"email": "user@example.com"
}
然后,使用收到的验证码进行验证:
{
"email": "user@example.com",
"otp": "123456"
}
通过这个简单的Node.js应用,你可以轻松地实现用户邮箱验证码的发送和验证功能。