Attached code:

HTML section (Jq required)

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <script src="./jquery.js"></script>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      div:nth-child(2) {
        display: none;
      }
      input {
        display: block;
        height: 40px;
        width: 200px;
        margin: 20px auto;
      }
      button:not(#email) {
        display: block;
        height: 30px;
        width: 70px;
        background: lightcoral;
        border: none;
        margin: 0 auto;
      }
      #email {
        display: block;
        height: 30px;
        width: 100px;
        margin: 0 auto;
      }
      ul {
        height: 50px;
        width: 200px;
        background: lightblue;
        margin: 0 auto;
        list-style: none;
      }
      li {
        height: 50px;
        width: 100px;
        float: left;
        text-align: center;
        line-height: 50px;
      }
      li:hover {
        background: lightgreen;
        cursor: pointer;
      }
    </style>
  </head>

  <body>
    <ul>
      <li id="regChange">registered</li>
      <li id="loginChange">The login</li>
    </ul>
    <div id="reg">
      <input type="text" placeholder="Email" id="user" />
      <input type="text" placeholder="Password" id="psd" />
      <input type="text" placeholder="Verification code" id="sendmail" />
      <button id="email">Send verification code</button> <button id="btn">registered</button>
    </div>
    <div id="login">
      <input type="text" placeholder="Username" id="loguser" />
      <input type="text" placeholder="Password" id="logpsd" />
      <button id="logbtn">The login</button>
    </div>

    <script>
        // Add listening events
      btn.addEventListener("click", clickHandler);
      logbtn.addEventListener("click", clickHandler);
      email.addEventListener("click", sendHandler);
      regChange.addEventListener("click", changeHandler);
      loginChange.addEventListener("click", changeHandler);

      function clickHandler(e) {
        if (this.textContent === "Registered") {
            // Jump if empty
          if(! user.value || ! psd.value || ! sendmail.value) { alert("Can't be empty");
            return;
          }
          // Click register to send email number, password, verification code to the background
          $.get(
            `http://localhost:1024/index/reg? user=${user.value}&psd=${ psd.value }&mail=${sendmail.value}`.function(res) {
                If hasUser is true, the user name already exists. Otherwise, the user is successfully registered
              if (res.hasUser) {
                alert("Registration failed");
                return;
              } else {
                alert("Registration successful ~");
              }
              // Hide the registration and display the login after success
              reg.style.display = "none";
              login.style.display = "block"; }); }else if (this.textContent === "Login") {
            // Same registration, cannot be empty
          if(! loguser.value || ! logpsd.value) { alert("Can't be empty");
            return;
          }
          // Click login to send the email number and password to the background
          $.get(
            `http://localhost:1024/index/login? user=${loguser.value}&psd=${ logpsd.value }`.function(res) {
                // If isUser is true, the object returned by the background is correct, and jump to the welcome page, otherwise failure
              if (res.isUser) {
                alert("Login successful");
                location.href = "./welcome.html";
              } else {
                alert("Incorrect username or password");
                return; }}); }}function sendHandler(e) {
        // Click to obtain the verification code and send it to the back end for comparison
        $.get(`http://localhost:1024/index/sendmail?${user.value}`);
      }

      function changeHandler(e) {
        // Click register login switch above
        if (e.target.textContent === "Registered") {
          reg.style.display = "block";
          login.style.display = "none";
        } else {
          reg.style.display = "none";
          login.style.display = "block"; }}</script>
  </body>
</html>
Copy the code

Node background: Third-party modules to be introduced include: Express framework, CORS, NodeMailer,

const express = require('express');// Introduce the Express framework.
const url = require('url');
const path = require('path');
const fs = require('fs');
const cors = require('cors');// Introduce cORS module (solve cross-domain problems)
const app = express();
// const bodyparser = require('body-parser');
const sendMail = require('./send');// This module is the mail module (found in my third Node article).


app.use(cors());
// The following header is similar to the HTTP request (another article writes about HTTP requests, which are also registered login)
app.all("*".function (req, res, next) {
    * indicates that any domain name is allowed to cross domains
    res.header("Access-Control-Allow-Origin"."*");
    res.header("Access-Control-Allow-Headers"."content-type");// The allowed header type
    res.header("Access-Control-Allow-Methods"."DELETE,PUT,POST,GET,OPTIONS");// The type of requests that are allowed across domains
    next();// Whether to continue down
})

// Register the interface
var count = ' ';// Create a null character to store the verification code, which can be called globally
app.get('/index/reg'.(req, res) = > {
    let search = url.parse(req.url).search;// Save the data from the front end
    files = path.join(__dirname, './user.txt');// Use a TXT to record the user name and password
    fs.readFile(files, 'utf8'.(err, data) = > {
        // Read the TXT file to determine whether there is a user name, and verify the verification code
        if (data.indexOf(search.split('&') [0= = = -])1 && search.split('&') [2].split('=') [1] === count) {
            fs.appendFile(files, search.split('&') [0] + '&' + search.split('&') [1]);If hasUser is true, the user already exists.
            res.send({
                hasUser: false
            });
        } else {
            // Return an object to the front end if the condition is not met
            res.send({
                hasUser: true}); }}); });// Login interface
app.get('/index/login'.(req, res) = > {
    let search = url.parse(req.url).search;// Save the data from the front end
    files = path.join(__dirname, './user.txt');
    // Read the TXT file and check whether there is a user name and password
    fs.readFile(files, 'utf8'.(err, data) = > {
        If isUser is true, the user name does not match the password.
        if (data.indexOf(search) === -1) {
            res.send({
                isUser: false
            });
        } else {
            res.send({
                isUser: true}); }}); });// Mailbox authentication interface
app.get('/index/sendmail'.(req, res) = > {
    count = ' ';// Initialize the captcha container
    let Email = url.parse(req.url).query;// Get the mailbox number from the front end
    for (let i = 0; i < 4; i++) {
        count += Math.floor(Math.random() * 10);// Generate 4 random numbers
    }
    sendMail.send(Email, count);// Call the mail sending module (pass in the registered mailbox, verification code)
    res.send(count);
});
// Listen to the service
app.listen(1024.() = > {
    console.log('Server Start~');
});
Copy the code

Attach the module for sending emails (also in my previous article)

// Import modules
 
const nodemailer = require("nodemailer");
 
// Create an object
 
let obj = {
 
transporter: nodemailer.createTransport({
 
service: "qq".// Operator qq mailbox netease //
 
port: 465.secure: true.auth: {
 
user: "**********@qq.com".// Sender's email address
 
pass: "* * * * * * * * * * * * * * *" // POP3 authorization code}}),// Send a parameter (email address, content)
 
send: function(mail, content) {
 
mailOptions = {
 
// Sender's email address
 
from: '"Hello World~" <***********@qq.com>'.to: mail,
 
subject: content,
 
text: content,
 
html: "<h1>" + content + "</h1>"
 
};
 
this.transporter.sendMail(mailOptions, (error, info) = > {
 
if (error) {
 
return console.log(error);
 
}
 
console.log("Message sent: %s", info.messageId); }); }};// Throw an object to receive
 
module.exports = obj;
Copy the code