Captcha验证码组件vue端
首先写一个验证码的vue组件,代码如下:
<template>
<pre><img v-bind:src="msg" class="user-avatar"></pre>
</template>
<script>
import axios from "axios"
export default {
name: 'Captcha',
data(){
return{
msg:'图片'
}
},
created() {
axios({
method:'get',
url:'captchapng',
responseType:'arraybuffer',
})
.then(response => {
return 'data:image/png;base64,' + btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte),'')
);
})
.then(data=>{
this.msg = data;
}).catch(ex=>{
console.error(ex);
});
}
}
</script>
nodejs端生成Captcha验证码
以下代码是将验证码写入了请求的session中
var session = require('express-session');
exports.captcha = function (req, res) {
var captchapng = require("captchapng")
var mynum = parseInt(Math.random()*9000+1000);
req.session.captcha = mynum;
var p = new captchapng(80,30,mynum); // 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.from(img,'base64');
res.writeHead(200, {
'Content-Type': 'image/png'
// 'Content-Type':'application/octet-stream;charset=utf-8'
});
res.end(imgbase64);
}
登录页引用
在登录的vue中import Captcha from './Captcha.vue'
实现的3个部分
</template>中:
<div @click="changecap">
<Captcha v-if="isRouterAlive"></Captcha>
</div>
<script>中:
import Captcha from './Captcha.vue'
export default {
name: 'Main',
components: {
Captcha
},
data () {
isRouterAlive: true
},
methods: {
changecap () {
// 刷新验证码
this.isRouterAlive = false
this.$nextTick(() => (this.isRouterAlive = true))
},
}
}
如果想绑定其他事件,比如验证失败需要立即刷新验证码,可自行绑定
axios 访问,node端验证
将axios请求的输入字段与req.session.captcha比较
var capt = req.body.textfield;
if(capt == req.session.captcha){}
这些代码都是我自己博客实践过的,当时网上找的参考资料也找不见了,写这里备注