验证码(CAPTCHA)是一种用于验证用户是否为人类的程序,通常用于防止自动化程序(如机器人)滥用服务。常见的验证码类型包括图片验证码、短信验证码和滑动验证码等。
以下是一个使用JavaScript实现简单图片验证码的示例:
我们可以使用canvas
元素来生成验证码图片。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>验证码示例</title>
<style>
#captcha {
border: 1px solid #ccc;
display: inline-block;
font-family: monospace;
font-size: 24px;
letter-spacing: 5px;
padding: 10px;
user-select: none;
}
</style>
</head>
<body>
<div id="captcha"></div>
<button onclick="generateCaptcha()">刷新验证码</button>
<script>
function generateCaptcha() {
const captchaContainer = document.getElementById('captcha');
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let captcha = '';
for (let i = 0; i < 6; i++) {
captcha += chars.charAt(Math.floor(Math.random() * chars.length));
}
const canvas = document.createElement('canvas');
canvas.width = 150;
canvas.height = 50;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#f2f2f2';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.font = 'bold 24px Arial';
ctx.fillStyle = '#333';
ctx.fillText(captcha, 10, 35);
// 添加干扰线
for (let i = 0; i < 5; i++) {
ctx.beginPath();
ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.strokeStyle = '#ccc';
ctx.stroke();
}
captchaContainer.innerHTML = '';
captchaContainer.appendChild(canvas);
}
// 初始化验证码
generateCaptcha();
</script>
</body>
</html>
在后端,你需要验证用户输入的验证码是否正确。以下是一个简单的Node.js示例:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
let currentCaptcha = '';
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/verify', (req, res) => {
const userInput = req.body.captcha;
if (userInput === currentCaptcha) {
res.send('验证码正确!');
} else {
res.send('验证码错误,请重试!');
}
});
app.post('/generate', (req, res) => {
// 生成新的验证码并更新currentCaptcha
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
currentCaptcha = '';
for (let i = 0; i < 6; i++) {
currentCaptcha += chars.charAt(Math.floor(Math.random() * chars.length));
}
res.send(currentCaptcha);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
在前端页面中,你需要添加表单来提交用户输入的验证码,并与后端进行交互。
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ... -->
</head>
<body>
<div id="captcha"></div>
<button onclick="generateCaptcha()">刷新验证码</button>
<form action="/verify" method="post">
<input type="text" name="captcha" placeholder="输入验证码">
<button type="submit">提交</button>
</form>
<script>
// ... generateCaptcha function
async function generateCaptcha() {
const response = await fetch('/generate');
const captcha = await response.text();
// 更新canvas显示的验证码
// ...
}
</script>
</body>
</html>
通过以上示例,你可以实现一个简单的图片验证码系统。根据实际需求,你可以进一步优化和扩展功能。