首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

js实现验证码

验证码(CAPTCHA)是一种用于验证用户是否为人类的程序,通常用于防止自动化程序(如机器人)滥用服务。常见的验证码类型包括图片验证码、短信验证码和滑动验证码等。

以下是一个使用JavaScript实现简单图片验证码的示例:

1. 生成验证码图片

我们可以使用canvas元素来生成验证码图片。

代码语言:txt
复制
<!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>

2. 验证用户输入

在后端,你需要验证用户输入的验证码是否正确。以下是一个简单的Node.js示例:

代码语言:txt
复制
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');
});

3. 前端与后端交互

在前端页面中,你需要添加表单来提交用户输入的验证码,并与后端进行交互。

代码语言:txt
复制
<!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>

优势

  1. 防止自动化攻击:有效防止机器人注册、登录等行为。
  2. 提高安全性:增加系统安全性,减少恶意行为。

应用场景

  1. 用户注册:防止机器人批量注册。
  2. 登录验证:确保登录用户为人类。
  3. 评论区:防止垃圾评论。

注意事项

  1. 用户体验:验证码不应过于复杂,以免影响用户体验。
  2. 可访问性:为视觉障碍用户提供音频验证码等替代方案。

通过以上示例,你可以实现一个简单的图片验证码系统。根据实际需求,你可以进一步优化和扩展功能。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

5分31秒

python实现验证码识别ddddocr

11分56秒

27、尚硅谷_用户模块_邮箱验证码激活功能的实现.wmv

11分18秒

11. 尚硅谷_Zepto_ajax案例_实现接收一条验证码.avi

1分7秒

基于koa实现的微信JS-SDK调用Demo

15分26秒

day12/上午/232-尚硅谷-尚融宝-发送验证码的前端调用实现

7分28秒

python中生成验证码的库

51分57秒

14. 尚硅谷_Zepto_实战练习JS交互功能实现.avi

22分54秒

213、商城业务-认证服务-整合短信验证码

28分34秒

214、商城业务-认证服务-验证码防刷校验

6分30秒

【技术创作101训练营】腾讯云云函数实现微信JS-SDK调用

29分6秒

01.尚硅谷_JS基础_JS简介

2分36秒

8个免费JS加密工具-[JS加密]

扫码

添加站长 进交流群

领取专属 10元无门槛券

手把手带您无忧上云

扫码加入开发者社群

相关资讯

热门标签

活动推荐

    运营活动

    活动名称
    广告关闭
    领券