express+svg-captcha验证码实现及验证(附前后端代码具体实现)

安装:

npm install --save svg-captcha

使用svg-captcha生成验证码并返回给前台

const express = require('express');
const svgCaptcha = require('svg-captcha');
const router = express.Router();
router.get('/',(req, res)=>{
     
  const cap = svgCaptcha.create({
     
          // 翻转颜色
          inverse: false,
          // 字体大小
          fontSize: 36,
          // 噪声线条数
          noise: 3,
          // 宽度
          width: 80,
          // 高度
          height: 30,
      });
  req.session.captcha = cap.text; // session 存储验证码数值
  console.log(req.session)
  res.type('svg'); // 响应的类型
  res.send(cap.data)
})
 
module.exports = router;

进行测试发现没有返回值,排查错误后发现是没有注册session中间件,svg-captcha依赖session存储验证码信息

express-session是express中比较常用的处理session的中间件,使用npm安装

npm install express-session --save

session的认证机制必须依赖cookie,所以还应该同时安装一个cookie-parser

npm install cookie-parser --save

之后定义cookie解析器,注意,该定义必须写在路由分配之前:

app.use(cookieParser());

app.use(session({
     
secret: '12345',
name: 'name',
cookie: {
     maxAge: 60000},
resave: false,
saveUninitialized: true,
}));

各参数意义:

secret:				用来对session数据进行加密的字符串.这个属性值为必须指定的属性。
name:					表示cookie的name,默认cookie的name是:connect.sid。
maxAge:				cookie过期时间,毫秒。
resave:				是指每次请求都重新设置session cookie,假设你的cookie是6000毫秒过期,每次请求都会再设置6000毫秒。
saveUninitialized:		是指无论有没有session cookie,每次请求都设置个session cookie ,默认给个标示为 connect.sid。

后端搭建完毕,测试输出,输出成功,收到svg格式验证码,配置vue前台。

vue前台使用 和 刷新验证码的小技巧

 <img  src="http://localhost:4000/captcha" alt="captcha"
  @click="getCaptcha" ref="captcha">

使用:img标签中的src和Date.now()刷新验证码

<script>
export default {
     
  methods: {
     
     // 获取一个新的图片验证码
      getCaptcha () {
     
        // 每次指定的src要不一样,img才会重新请求,可以使用Date.now()小技巧
        this.$refs.captcha.src = 'http://localhost:4000/captcha?time='+Date.now()
      }
  }
};
</script>

axios传给后台

import axios from 'axios'
Vue.prototype.$http = axios
<script>
export default {
     
  methods: {
     
    getCaptcha () {
     
        this.$refs.captcha.src = 'http://localhost:4000/captcha?time='+Date.now()
      },
      //axios发送登录请求,附带上验证码
    goLog() {
     
      console.log(this.data);
      this.$http
        .post("/api/login_pwd", {
     
            // 传输数据给后台
            account: this.name,
            password: this.pwd,
            verifiy: captcha
        })
        .then(res => {
     
          if (res.data.code === 0) {
     
            // 验证成功返回值为200进入主页面
            this.$router.push("/");
          } else {
     
            // 验证出错误时重新更新验证码
            this.getCaptcha()
          }
        })
        .catch(err => {
     
          console.log(err);
        });
    }
  }
};
</script>

nodejs后台验证 验证码操作(数据库为mongodb)

/*
用户名,密码,验证码 登陆(登录和注册一体化)
  1.数据库中有此用户,比对密码
  2.数据库中没此用户,直接注册
 */
router.post('/login_pwd', function (req, res) {
     
  const name = req.body.name   //前台提交的用户名
  const pwd = md5(req.body.pwd) //密码
  const captcha = req.body.captcha.toLowerCase()  //验证码,转小写
  console.log('/login_pwd', name, pwd, captcha, req.session)

  // 可以对用户名/密码格式进行检查, 如果非法, 返回提示信息
  if(captcha!==req.session.captcha) {
     
    return res.send({
     code: 1, msg: '验证码不正确'})
  }
  // 验证通过,删除保存的验证码
  delete req.session.captcha

  UserModel.findOne({
     name}, function (err, user) {
     
    if (user) {
     
      console.log('findUser', user)
      if (user.pwd !== pwd) {
     
        res.send({
     code: 1, msg: '用户名或密码不正确!'})
      } else {
     
        req.session.userid = user._id
        res.send({
     code: 0, data: {
     _id: user._id, name: user.name, phone: user.phone}})
      }
    } else {
     
      const userModel = new UserModel({
     name, pwd})
      userModel.save(function (err, user) {
     
        // 向浏览器端返回cookie(key=value)
        // res.cookie('userid', user._id, {maxAge: 1000*60*60*24*7})
        req.session.userid = user._id
        const data = {
     _id: user._id, name: user.name}
        // 3.2. 返回数据(新的user)
        res.send({
     code: 0, data})
      })
    }
  })
})

至此整个过程完成

你可能感兴趣的:(前端)