本文小编为大家详细介绍“怎么用纯JavaScript生成图片或滑块式验证码功能”,内容详细,步骤清晰,细节处理妥当,希望这篇“怎么用纯JavaScript生成图片或滑块式验证码功能”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
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 = captchaNumbervar p = new captchapng(80,20, captchaNumber); // width,height,numeric captchap.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 captchaUsage (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')})
读到这里,这篇“怎么用纯JavaScript生成图片或滑块式验证码功能”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注编程网行业资讯频道。