``` //用于生成验证ma const svgCaptcha = require("svg-captcha") //mysql 用于在数据库中查找前端输入的用户名和密码 const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '12345678', database: 'sys' }); connection.connect(); //redis数据库用于存储随机生成的验证码 //便于及时更新 const client = redis.createClient(); //redis 如果没有启动redis,会报错 //redis 启动命令 redis-server //新建terminal 输入redis-cli client.on("error", function (err) { console.log("Trror" + err); }) //生成token 方便redis存储和替换 function getID(length) { return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36); } //验证码 app.get("/cap", (req, res) => { const cap = svgCaptcha.create(); //cap=>{data:...,text:jsoa} //text:随机生成的四位验证码 //data:传递给前端的验证码的图片 let text = cap.text; res.type("svg"); //生成一个ID redis保存 并传递给前端 let captchaId = getID(10) client.set(captchaId, text) res.send({ cap, captchaId }) return }) //前端引用图片 // <span dangerouslySetInnerHTML={{ __html: captcha }} onClick={() => this.getcaptcha()}></span> //登陆 app.post("/getlogin", async (req, res) => { let { username, password, verification, captchaId } = req.body; let redisCaptcha = await new Promise((resolve) => { client.get(captchaId, function (err, res) { return resolve(res) }) }) if (verification === redisCaptcha) { } else { res.send({ code: 0, message: "验证码错误或过期" }) return } //数据库中查找数据 connection.query(`SELECT * FROM table where username='${username}' &&passwrd='${password}'`, function (error, results, fields) { if (error) throw error; if (results[0]) { res.send({ code: 1, message: "登陆成功" }) } else { res.send({ code: 0, message: "用户名或密码错误" }) return } }); }) ```