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

有一些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框架设计的验证码生成模块。

https://github.com/napa3um/node-captcha

安装&示例:

$ 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(`

`)

})

app.post(‘/login’, (req, res) => {

res.type(‘html’)

res.end(`

CAPTCHA VALID: ${ captcha.check(req, req.body[captchaFieldName]) }

`)

})

app.listen(8080, () => {

console.log(‘server started’)

})

前端滑块验证

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

https://gitee.com/LongbowEnterprise/SliderCaptcha