我正在使用 svg-captcha 库(链接 npm),但是我找不到验证从用户发送到服务器的验证码的方法。
现在我可以用它来生成验证码并返回客户端。 这是我的代码:
app.get('/captcha', function (req, res) {
var captcha = svgCaptcha.create();
req.session.captcha = captcha.text;
res.type('svg');
res.status(200).send(captcha.data);
});
我使用node.js
非常感谢
也许我来晚了,但您可以为验证码创建一个唯一的 id,然后将该 uid 和验证码文本保存在您的服务器上,并在响应时发送带有验证码数据的验证码 uid。因此,用户可以从那里发送请求,包括从客户端解析的验证码文本和请求中的验证码 uid。然后您可以将其与存储的验证码进行比较。 以下是用户获得验证码后收到的内容:
{
"key": "some kind of uid",
"content": "<svg your catpcha data></svg>"
}
这是他们发回的内容:
{
"ckey": "the captcha uid they received",
"cvalue": "value of the captcha they solve",
"some_params": "some values"
}
这是我在后端nodejs中生成验证码的代码
exports.getCaptcha = (req, res) => {
try {
var captcha = svgCaptcha.create();
session.captcha = captcha.text;
return res.status(200).json({ captcha: captcha.data});
} catch (error) {
console.error('Error generating captcha:', error);
return res.status(500).json({ error: 'Failed to generate captcha' });
}
}
exports.signin = async (req, res) => {
try {
const { username, password } = req.body;
const captchaInput = req.body.captcha;
if(captchaInput !== session.captcha)
{
return res.status(422).json({
error:"Captcha validation failed",
})
}
const user = await User.findOne({where: {username:username,status:1} });
if (!user) {
return res.status(400).json({
error: "Username does not exist"
});
} else {
const passwordMatch = await bcrypt.compare(password, user.encry_password);
if (!passwordMatch) {
return res.status(422).json({
error: "Username and password do not match"
});
} else {
const token = jwt.sign({ id: user.id }, process.env.SECRET_KEY);
res.cookie("token", token, { expires: new Date(Date.now() + 999) });
const { id, name, username, email, mobile_no, role } = user;
return res.status(200).json({
token,
result: { id, name, username, email, mobile_no, role },
});
}
}
} catch (err) {
res.status(500).json({
error: "something went wrong "+err,
});
}
};