前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关于TypeScript实现后端发送给前端验证码图片和后端校验前端验证码

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

原创
作者头像
是谁抢了www名字
发布2024-09-24 20:02:07
850
发布2024-09-24 20:02:07
举报
文章被收录于专栏:后端技术讨论
代码语言: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;

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
验证码
腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档