Node.JS用纯JavaScript生成图片或滑块式验证码功能

2022-10-16,,,,

有一些node.js图片生成类库,比如node-captcha等的类库,需要c/c++程序生成图片。跨平台部署不是很方便。这里介绍几个用纯js实现的图片验证码生成模块。

captchapng

用纯javascript实现的验证码生成模块。

https://github.com/georgechan/captchapng

安装简单,依赖少:

npm install captchapng

示例:

var captchapng = require('captchapng');
app.get('/sign/captcha.png', function(req, res) {
var captchanumber  = parseint(math.random() * 9000 + 1000)
req.session.captcha = captchanumber
var p = new captchapng(80,20, captchanumber); // width,height,numeric captcha
p.color(0, 0, 0, 0); // first color: background (red, green, blue, alpha)
p.color(80, 80, 80, 255); // second color: paint (red, green, blue, alpha)
var img = p.getbase64();
var imgbase64 = new buffer(img,'base64');
res.writehead(200, {
'content-type': 'image/png'
});
res.end(imgbase64);
})

express + captcha

为express框架设计的验证码生成模块。

安装&示例:

$ npm install captcha
usage (for express 4)
'use strict'
const express = require('express')
const session = require('express-session')
const bodyparser = require('body-parser')
const captchaurl = '/captcha.jpg'
const captchaid = 'captcha'
const captchafieldname = 'captcha'
const captcha = require('./captcha').create({ cookie: captchaid })
const app = express()
app.use(session({
secret: 'keyboard cat',
resave: false,
saveuninitialized: true,
}))
app.use(bodyparser.urlencoded({ extended: false }))
app.get(captchaurl, captcha.image())
app.get('/', (req, res) => {
res.type('html')
res.end(`
<img src="${ captchaurl }"/>
<form action="/login" method="post">
<input type="text" name="${ captchafieldname }"/>
<input type="submit"/>
</form>
`)
})
app.post('/login', (req, res) => {
res.type('html')
res.end(`
<p>captcha valid: ${ captcha.check(req, req.body[captchafieldname]) }</p>
`)
})
app.listen(8080, () => {
console.log('server started')
})

前端滑块验证

前端生成轨迹发送到后端验证,输入简单,但是容易被破解。

 

https://gitee.com/longbowenterprise/slidercaptcha

总结

以上所述是小编给大家介绍的node.js用纯javascript生成图片或滑块式验证码功能,希望对大家有所帮助

《Node.JS用纯JavaScript生成图片或滑块式验证码功能.doc》

下载本文的Word格式文档,以方便收藏与打印。