关于TypeScript实现后端发送给前端验证码图片和后端校验前端验证码

2024-09-24 20:02:07 浏览数 (3)

代码语言:txt复制
import { createCanvas, loadImage, registerFont } from 'canvas';
import express from "express"
import multer from 'multer'; // 用于处理 multipart/form-data 请求

const router = express.Router();
const upload = multer(); // 使用 Multer 处理 multipart/form-data

let store_captcha:string = '';
router.get('/captcha', async (req, res) => {
    try {
        // 生成随机验证码字符串
        const captchaText = generateCaptcha();

        // 创建画布
        const canvas = createCanvas(100, 40);
        const ctx = canvas.getContext('2d');

        // 绘制背景颜色
        ctx.fillStyle = '#ecedee';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 绘制随机线条
        for (let i = 0; i < 5; i  ) {
            ctx.strokeStyle = randomColor();
            ctx.beginPath();
            ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.stroke();
        }

        // 绘制验证码文本
        ctx.font = 'bold 30px YourFontFamily';
        ctx.fillStyle = '#6c757d';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(captchaText, canvas.width / 2, canvas.height / 2);

        // 将生成的验证码字符串存储起来
        storeCaptcha(captchaText);

        // 返回生成的验证码图片
        res.type('png');
        canvas.createJPEGStream().pipe(res);
    } catch (error) {
        console.error(error);
        res.status(500).send('Internal Server Error');
    }
});

router.post('/validate', upload.none(), (req, res) => {
    const { captcha } = req.body;
    if (!captcha) {
        res.status(400).json({ success: false, message: '验证码不能为空' });
        return;
    }

    if (captcha.toLowerCase() === store_captcha.toLowerCase()) {
        // 清空已存储的验证码
        store_captcha = '';
        res.json({ success: true, message: '验证成功' });
    } else {
        res.json({ success: false, message: '验证失败' });
    }
});

function generateCaptcha(): string {
    // 定义验证码字符集
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let captcha = '';
    for (let i = 0; i < 4; i  ) {
        // 生成0到字符集长度之间的随机索引
        const index = Math.floor(Math.random() * chars.length);
        captcha  = chars[index];
    }
    return captcha;
}

function randomColor(): string {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    return `rgb(${r},${g},${b})`;
}

function storeCaptcha(text: string): void {
    // 实现你的存储逻辑
    store_captcha = text;
}


export default router;

1 人点赞