node生成图片验证码

首先安装 svg-captcha

npm i svg-captcha --save

后端接口:
在routes中新建文件 captcha.js

var express = require('express')
var router = express.Router()

const svgCaptcha = require('svg-captcha')

router.get('/', function(req, res, next) {
	var captcha = svgCaptcha.create({
		inverse: false, // 翻转颜色 
		fontSize: 48, // 字体大小 
		noise: 2, // 噪声线条数 
		width: req.query.width, // 宽度 
		height: req.query.height, // 高度 
		size: 4,// 验证码长度
		ignoreChars: '0o1i', // 验证码字符中排除 0o1i
	});
	// 保存到session,忽略大小写 
	req.session = captcha.text.toLowerCase();
	// console.log(req.session); //0xtg 生成的验证码
	//保存到cookie 方便前端调用验证
	res.cookie('captcha', req.session);
	res.setHeader('Content-Type', 'image/svg+xml');
	res.write(String(captcha.data));
	res.end();
})
module.exports = router

在app.js中

const captchaRouter = require('./routes/captcha')
app.use('/captcha', captchaRouter)

前端调用:

// 结构
<el-form-item prop="image_code" :rules="{required:true,message:'请输入验证码',trigger:'blur'}">
    <el-input v-model="form.image_code" placeholder="验证码" @keyup.enter.native="submit('form')" class="w320">
       <template slot="prepend">
          <img :src="require('@/assets/images/pass.png')" width="15" height="15">
       </template>
     </el-input>
     <img :src="imgSrc" class="pointer imgsize" @click="getImageCode" />
 </el-form-item>

// 在methods中 哪里要变更图形验证码 就调用这个函数就可以啦
getImageCode() {
   this.imgSrc = `/api/teacher/captcha?width=100&height=40&nonce=${new Date().getTime()}`
},

一般 图形验证码 会在访问登陆接口的时候传给后端
所以在登陆接口要获取 图形验证码的内容,判断是否正确
下面是我的登陆接口:

var express = require('express')
var router = express.Router()

const db = require('../../db/config')

router.post('/', function(req, res, next) {
	const account = req.body.account
	const password = req.body.password
	const image_code = req.body.image_code
	const captcha = req.cookies.captcha

	let sql = `select * from teacher where account = ? and password = ?`
	db.query(sql, [account, password], (err, result) => {
		if (err) {
			console.log(err)
		} else {
			if (image_code.toLowerCase() !== captcha) {
				res.render('teacher/login', {
					data: JSON.stringify({
						code: 0,
						msg: '验证码输入错误',
						data: null,
						success: false
					})
				})
			} else if (result.length > 0) {
				res.render('teacher/login', {
					data: JSON.stringify({
						code: 0,
						msg: '账号正确',
						data: null,
						success: true
					})
				})
			} else {
				res.render('teacher/login', {
					data: JSON.stringify({
						code: 0,
						msg: '账号或密码输入错误',
						data: null,
						success: false
					})
				})
			}
		}
	})
})
module.exports = router

你可能感兴趣的:(node精选)