使用Node.js发送邮箱验证码

在Web应用开发中,用户注册和身份验证是常见的功能之一。为了提高安全性和验证用户的有效性,通常会使用邮箱验证码。本文将介绍如何使用Node.js发送邮箱验证码,以增强用户注册流程的安全性。

准备工作

首先,确保你已经安装了Node.js和npm。然后,创建一个新的Node.js项目,并在项目目录中运行以下命令安装所需的依赖:

npm init -y
npm install nodemailer express body-parser

这将安装用于发送邮件的nodemailer库,以及用于创建Web服务器和处理请求的expressbody-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.comyour_email_password为你的发件人邮箱和密码。

测试

使用Postman或其他工具发送POST请求进行测试。首先,发送一个请求以获取验证码:

{
  "email": "user@example.com"
}

然后,使用收到的验证码进行验证:

{
  "email": "user@example.com",
  "otp": "123456"
}

通过这个简单的Node.js应用,你可以轻松地实现用户邮箱验证码的发送和验证功能。

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值