Node+express中添加验证码

验证码在平时访问网站中非常常见,其作用是能够有效的避免机器操作,恶意攻击。

1.使用的包
svg-captcha
  在node.js或express.js中生成svg captcha验证码
cookie-parser
  存储验证码的值

//安装
npm i svg-captcha cookie-parser express-session

2.index.js代码

// 验证码
let svgCaptcha=require('svg-captcha');
// cookie
let cookoeParser=require('cookie-parser');
// 启用cookie
app.use(cookoeParser());
// 启用session
let session=require('express-session')
app.use(session());
// 创建一个验证码的路由
app.get('/verifyCode',(req,res)=>{
    // 创建验证码
    var captcha = svgCaptcha.create({
        color: true, // 验证码的字符是否有颜色,默认没有,如果设定了背景,则默认有
        inverse:false,// 反转颜色
        background: '#eee' // 验证码图片背景颜色
        width:100, //  宽度
        height:40, // 高度
        fontSize:48, // 字体大小
        size:4, // 验证码的长度
        noise:3, // 干扰线条的数量
        ignoreChars: '0oO1ilI' // 验证码字符中排除 0o1i 这些较难识别的
    });
    // session里面也放一份,并且文本不区分大小写
    req.session=captcha.text.toLowerCase();
    // cookie放一份
    res.cookie('captcha',req.session);
    res.send(captcha.data);
    // 往session,cookie中都存入一个验证码,并且把验证码显示在页面上
})

3.index.html页面调用验证码

调用的时候使用ajax的方式调用,每次点击图片也重新调用验证码

 <form  action="" method="">
        <input type="text"  name="name" required autocomplete="on" autofocus>
        <input type="password" name="password" >
        <input type="text"  name="verCode" placeholder="请输入验证码"   required >
        <div id="verify"></div>
 </form>
<script>
function getVerify(){
    $.ajax({
        url:'/verifyCode?t='+Math.random(),
        type:'get',
        success:function(data){
            $('#verify').html(data);
        }
    })
}
getVerify()
$('#verify').on('click',function(){
    getVerify()
})
</script>

生产的验证码如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sea9528/article/details/105658717