node.js 实现验证码
效果图1

效果图2、3


后端:
- 安装 svg-captcha
npm install svg-captcha - 引入
const svgCaptcha = require('svg-captcha'); - 使用生成验证码
const cap = svgCaptcha.create({
size: 4,
width: 160,
height:40,
fontSize: 50,
ignoreChars: '0oO1ilI',
noise: 2,// 干扰线
color: true,
background: '#eee'
})
- 路由
router.get('/auth', async(ctx) => {
console.log(ctx.request.query.code);
const getCode = ctx.request.query.code
if(getCode === this.cap.text){
ctx.body = {
message: '验证码正确'
}
} else {
ctx.body = {
message: '验证码错误'
}
}
})
- 前端使用
function getCode() {
$.ajax({
url: 'http://localhost:8888/code',
method: 'GET',
success: (res) => {
// console.log(res);
var dom1 = document.getElementById("code")
dom1.innerHTML = res
}
})
}
(function(){
getCode()
const input = document.getElementById("input")
const login = document.getElementById("login")
login.addEventListener('click', () => {
console.log(input.value);
$.ajax({
url: `http://localhost:8888/auth?code=${input.value}`,
method: "GET",
success: (res)=> {
alert(res.message)
}
})
})
})()

浙公网安备 33010602011771号