This article shares with you how to use node to generate verification codes. It has certain reference value. Friends in need can refer to it.
Network security is always an important topic. For example, when you find that someone is maliciously requesting the email registration interface of your website, then you can consider adding a verification code on the server to improve Regarding website security, this article will talk about how to use node to implement a verification code.
The front-end display is as follows:
Note that when the user clicks on the picture, a new picture needs to be refreshed, because The browser will cache the same image, so the caching situation needs to be dealt with here. Here I use to add the current timestamp to the image address to achieve the purpose of refreshing. The code is as follows:
<p> <input> <img alt="How to use node to generate verification code" > </p>
<script></script> <script> new Vue({ el: '#app', data: { authImgUrl: '' }, created () { this.authImgUrl = 'http://localhost:3000/' }, methods: { changeAuthImg () { this.authImgUrl = 'http://localhost:3000/' + '?' + new Date().getTime() } } }) </script>
First, npm installs the gd-bmp module: npm i gd-bmp --save
This is an efficient and 100% js application graphics library that supports drawing points, lines, curves, rectangles, circles, etc. The address is as follows:
https://github .com/zengming00...
The backend code is as follows:
var http = require('http') var BMP24 = require('gd-bmp').BMP24 // 生成随机数 function rand (min, max) { return Math.random() * (max - min + 1) + min | 0 // 特殊的技巧,|0可以强制转换为整数,向下舍入 } // 制造验证码图片 function makeCapcha() { let img = new BMP24(100, 40) // 长100, 高40 // 背景颜色 img.fillRect(0, 0, 100, 40, 0xffffff) // 白色 // 画曲线 var w = img.w / 2 var h = img.h var color = rand(0, 0xffffff) var y1 = rand(-5, 5) // Y轴位置调整 var w2 = rand(10, 15) // 数值越小频率越高 var h3 = rand(3, 5) //数值越小幅度越大 var bl = rand(1, 5) for (let i = -w; i <p>The function makeCapcha is used to generate the verification code. Because the image format is bmp, the response header type is set to <code>image/ bmp</code>, and finally, return the generated image to the client through <code>res.end(img.getFileData())</code>. </p><p class="post-topheader custom- pt0">Related recommendations:</p><p class="post-topheader custom- pt0"><a href="http://www.php.cn/js-tutorial-406881.html" target="_blank" title="关于TypeScript在node项目中的实践分析">Practical analysis of TypeScript in node projects</a><br></p><div></div>
The above is the detailed content of How to use node to generate verification code. For more information, please follow other related articles on the PHP Chinese website!