使用svg-captcha插件在node.js中生成svg格式的验证码。
1、安装
npm install --save svg-captcha
2、在express中使用方法
// 导入svg-captcha模块
const svgCaptcha = require('svg-captcha');
//创建Router对象
const router = express.Router();
router.get('/captcha',function (req, resp) {
const cap = svgCaptcha.create({size:4,noise:1,ignoreChars:'0o1i',background:'#DFE1CC'});
//const cap = svgCaptcha.createMathExpr({mathMin: 1,mathMax:9,background:'#fffffd'});
req.session.captcha = cap.text; // session 存储
console.log(req.session.captcha);
//console.log(cap.data);
resp.type('svg'); // 响应的类型
resp.send(cap.data);
});
//登录操作 http://localhost:8080/student/login
router.post("/login", function (req, resp) {
//定义返回的对象
let obj = {succ:false,msg:""};
//判断验证码
//从session获取图片验证码
let yzm = req.session.captcha.toUpperCase();
if(params.yzm.toUpperCase()==yzm){
obj.msg="验证码正确";
resp.json(obj);
}else{
obj.msg="验证码错误";
resp.json(obj);
}
});
3、前端页面
function getcaptcha(){
$("#yzmimg").attr("src","http://localhost:8080/student/captcha?r="+new Date().getTime());
}
<img id="yzmimg" src="http://localhost:8080/student/captcha" width="100" height="34" onclick="getcaptcha()"/>