svg-captcha 生成图片验证码

104 阅读1分钟

svg-captcha - npm (npmjs.com)

npm install --save svg-captcha
const express = require('express');
const {getCaptchaService} = require("../service/captchaService");
const router = express.Router();

// 生成验证码
router.get('/', async function (req, res, next) {
    const captcha = await getCaptchaService()
    req.session.captcha = captcha.text
    res.setHeader('Content-Type', 'image/svg+xml')
    res.send(captcha.data)
})

module.exports = router;
const svgCaptcha = require('svg-captcha');
module.exports.getCaptchaService = async (req, res) => {
    return svgCaptcha.create({
        size: 4,
        ignoreChars: 'ilIL10Oo',
        noise: 6,
        color: true
    })
}

因为此时将 svg 保存到了 session 中,需要安装 express-session:

express-session - npm (npmjs.com)

app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true,
}))