逻辑引导:服务端使用 svg-captcha 包进行返回图形验证码传递给前台,并将验证码的值保存到数据库。前端通过展示图形验证码,并将用户输入的验证码值传递到服务端,服务端进行校验并返回对应的数据。

接口的实现

打开之前的服务端项目(koa-project),并安装 svg-captcha 包至生产环境

  1. cd koa-second
  2. yarn add svg-captcha -S

服务端的目录结构(省略部分与svg-captcha不相关的文件)
|- - - .vscode
|- - - config
|- - - **node_modules
|- - - src
|- - - **api
|- - - **PublicController.js
|- - - routers
|- - - **publicRouter.js
|- - - **routers.js
|- - - **index.js
|- - - **.babelrc
|- - - package.json

PublicController.js

  1. import svgCaptcha from 'svg-captcha'
  2. class PublicColltroller {
  3. constructor() { }
  4. async getCaptcha(ctx) {
  5. const newCaptcha = svgCaptcha.create({
  6. size: 4,//验证码有几位
  7. ignoreChars: '0o1il',//忽略的字母不会出现在验证码中
  8. color: true,//彩色
  9. noise: Math.floor(Math.random() * 5),//干扰线
  10. width: 150,//宽
  11. height: 50//高
  12. //更多的详细配置可以svg-captcha中看到
  13. })
  14. console.log(newCaptcha)
  15. ctx.body = {
  16. code: 200,
  17. data: newCaptcha.data
  18. }
  19. }
  20. }
  21. export default new PublicColltroller();

publicRouter.js

  1. import Router from 'koa-router'
  2. import publicController from '../api/PublicController'
  3. const router = new Router()
  4. router.get('/getCaptcha', publicController.getCaptcha)
  5. export default router

routers.js

  1. import combineRouters from 'koa-combine-routers'
  2. import publicRouter from './publicRouter'
  3. export default combineRouters(publicRouter)

访问接口之后会看到一个svg标签,这就是由服务端(svg-captcha)生成的图形验证码
深度截图_选择区域_20200725111339.png

接入前端

通过 axios 请求接口,并点击切换:

  1. <template>
  2. <div id="app">
  3. <div class="imooc-tiper" v-html="svg" @click="getCaptcha()"></div>
  4. </div>
  5. </template>
  6. <script>
  7. import axios from 'axios'
  8. export default {
  9. data () {
  10. return {
  11. svg: '验证码加载中...'
  12. }
  13. },
  14. mounted () {
  15. this.getCaptcha()
  16. },
  17. methods: {
  18. getCaptcha () {
  19. const that = this
  20. axios.get('http://localhost:3000/getCaptcha').then(res => {
  21. if (res.status !== 200 || res.data.code !== 200) {
  22. that.svg = '请点击获取验证码'
  23. return
  24. }
  25. that.svg = res.data.data
  26. })
  27. }
  28. }
  29. }
  30. </script>
  31. <style lang="scss">
  32. .imooc-tiper {
  33. height: 44px;
  34. line-height: 44px;
  35. text-align: center;
  36. }
  37. </style>