node.js 實現驗證碼
阿新 • • 發佈:2021-12-31
效果圖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) } }) }) })()