逻辑引导:服务端使用 svg-captcha 包进行返回图形验证码传递给前台,并将验证码的值保存到数据库。前端通过展示图形验证码,并将用户输入的验证码值传递到服务端,服务端进行校验并返回对应的数据。
接口的实现
打开之前的服务端项目(koa-project),并安装 svg-captcha 包至生产环境
cd koa-secondyarn 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
import svgCaptcha from 'svg-captcha'class PublicColltroller {constructor() { }async getCaptcha(ctx) {const newCaptcha = svgCaptcha.create({size: 4,//验证码有几位ignoreChars: '0o1il',//忽略的字母不会出现在验证码中color: true,//彩色noise: Math.floor(Math.random() * 5),//干扰线width: 150,//宽height: 50//高//更多的详细配置可以svg-captcha中看到})console.log(newCaptcha)ctx.body = {code: 200,data: newCaptcha.data}}}export default new PublicColltroller();
publicRouter.js
import Router from 'koa-router'import publicController from '../api/PublicController'const router = new Router()router.get('/getCaptcha', publicController.getCaptcha)export default router
routers.js
import combineRouters from 'koa-combine-routers'import publicRouter from './publicRouter'export default combineRouters(publicRouter)
访问接口之后会看到一个svg标签,这就是由服务端(svg-captcha)生成的图形验证码
接入前端
通过 axios 请求接口,并点击切换:
<template><div id="app"><div class="imooc-tiper" v-html="svg" @click="getCaptcha()"></div></div></template><script>import axios from 'axios'export default {data () {return {svg: '验证码加载中...'}},mounted () {this.getCaptcha()},methods: {getCaptcha () {const that = thisaxios.get('http://localhost:3000/getCaptcha').then(res => {if (res.status !== 200 || res.data.code !== 200) {that.svg = '请点击获取验证码'return}that.svg = res.data.data})}}}</script><style lang="scss">.imooc-tiper {height: 44px;line-height: 44px;text-align: center;}</style>
