This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging

NodeJS back-end development 10 generate image verification code and verification

A lot of the time we put a captcha on the login page or for example some of the lottery entries.

And then verify it in the background. By placing a picture verification code, the robot can be prevented from violently scanning the retry system interface.

Of course, some websites are designed to prevent normal users from using the captcha (like a ticket website before…).

Let’s just look at the effect

As shown above, the login form submits a user name and a verification code.

The background obtains the input verification code and verifies it.

If the verification fails, the user needs to click the image to generate a new verification code image, and then continue to submit the form verification.

Incorrect image verification code

As shown below, this example disables the user from continuing to log in and prints the prompt.

The principle of

A user xiaobai refreshes the login page, and the background generates a verification code according to a given text, and records the text. (Stored in the server session)

When the user who received the image captcha corresponding to this number submits the form. (Xiao Bai needs to submit the text with the same verification code picture).

The background obtains the corresponding text from the session and verifies it.

If the verification is successful, it is regarded as the manual operation of Xiaobai and the follow-up operation is continued.

npm install -S svg-captcha
Copy the code

The core code is as follows:

const express = require('express');
const session = require('express-session');
const serveStatic = require('serve-static');
const bodyParser = require('body-parser');

const leiXueWeiApp = express();
// parse application/x-www-form-urlencoded so that req will has a body attribute
app.use(bodyParser.urlencoded({ extended: false }))

leiXueWeiApp.use(serveStatic('./public'));
const port = 12024;

leiXueWeiApp.use(session({
  secret: 'Lei School Committee mySecret2021'.resave: false.saveUninitialized: true.cookie: { secure: false}}))const svgCaptcha = require('svg-captcha');
// a function to generate captcha and display on user screen
const captChaHandler = function(req, res){
    var captcha = svgCaptcha.create();
    req.session.captcha = captcha.text;
    res.type('svg');
    res.status(200).send(captcha.data);
}

leiXueWeiApp.get('/captcha',captChaHandler);

//user will submit form with code in request body and login handler will get captcha from session and check it with given code
leiXueWeiApp.post('/login'.function(req, res){
    console.log('try login');
    console.log([Lei School Committee] Body :', req.body);   
    var captchaCode = req.session.captcha
    console.log([Lei School Committee] captchaCode:', captchaCode)
    if(req.body && req.body.code == captchaCode){
        res.status(200).send(req.body.user + "Login verification successful!"); 
    }else{
        console.log('[lei Xuechai] Verification code verification failed ');
        res.status(400).send("BadRequest, the verification code is wrong!"); }});console.log('listening port ' + port);
leiXueWeiApp.listen(port);
Copy the code

In response, we could write code similar to the following on the page (incomplete, focusing only on the core implementation)

<form class="leixuewei" >Name:<input type="text" id="username" value="Lei School Committee" /><br/>Verification code:<input type="text" id="leiXueWeiCode" value="" />&nbsp;<img class="captcha" src="/captcha" οnclick={$(event.target).attr('src', '/captcha? '+Math.random())} /> <br/>
<input type="submit" value="Submit" />
</form>
<br/><div id="result"></div>
<script src="https://cdn.staticfile.org/jquery/3.4.0/jquery.min.js"></script>
<script>
$(document).ready(function() {$("form").submit(function(e){
        e.preventDefault();
        var userName = $("#username").val();
        var code = $("#leiXueWeiCode").val();
        $.ajax({
            type: 'post'.data: {user:userName, code: code},
            url: "http://localhost:12024/login/".success:function(data){$('#result').html(JSON.stringify(data)); },error:function(error){$("#result").html(JSON.stringify(error)); }})}); }Copy the code

To implement the following form:

By the way, the student committee also has this can pay attention to long-term reading => lei Student committee interesting programming story compilation or => Lei Student Committee NodeJS series

Continuous learning and continuous development, I am the Lei School committee! Programming is fun, but the key is to get the technology straight. Creation is not easy, please support a lot, click like collection to support the school committee!

For more code, check out the /Star: LearnNodeJS code download

Refer to the link

www.npmjs.com/package/svg…