Node.js 使用 Redis 存储验证码 - 实践指南
以下是在 Node.js 中使用 Redis 存储验证码的示例代码:
const redis = require('redis');
const client = redis.createClient();
// 设置验证码
function setVerificationCode(email, code) {
client.set(email, code, 'EX', 300); // 有效期为 5 分钟
}
// 获取验证码
function getVerificationCode(email, callback) {
client.get(email, (err, reply) => {
if (err) {
callback(err, null);
} else {
callback(null, reply);
}
});
}
// 示例使用
const email = 'test@example.com';
const code = '123456';
setVerificationCode(email, code);
getVerificationCode(email, (err, reply) => {
if (err) {
console.error(err);
} else {
console.log('验证码:', reply);
}
});
在上面的代码中,我们使用 redis 模块创建了一个 Redis 客户端,然后定义了 setVerificationCode 和 getVerificationCode 两个函数,分别用于设置验证码和获取验证码。
在 setVerificationCode 函数中,我们使用 client.set 方法将验证码存储到 Redis 中,并设置了一个有效期为 5 分钟。
在 getVerificationCode 函数中,我们使用 client.get 方法从 Redis 中获取验证码,并在获取成功后使用回调函数返回验证码。如果获取过程中出现了错误,我们将错误作为第一个参数传递给回调函数。
最后,我们在示例代码中使用了 setVerificationCode 和 getVerificationCode 两个函数来设置和获取验证码,以展示如何在 Node.js 中使用 Redis 存储验证码。
原文地址: https://www.cveoy.top/t/topic/mves 著作权归作者所有。请勿转载和采集!