Attached code :(compared with the previous with TXT implementation of no difference, just back-end database interface function)

Html:

<! 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 register 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

JS part: Express framework, CORS, Nodemailer is also used, and File System, Path module is not required

var MongoClient = require("mongodb").MongoClient;//mongoDb module is introduced
var mongoDB = "mongodb://localhost:27017/";// Initialize the address
const express = require("express"); // Introduce the Express framework.
const url = require("url");
const cors = require("cors"); // Introduce cORS module (solve cross-domain problems)
const app = express();
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)
    .query.split("&") [0]
    .split("=") [1]; // Save the data from the front end
  let query = url.parse(req.url).query.split("&");
  MongoClient.connect(// Connect to the database
    mongoDB,
    {
      useNewUrlParser: true
    },
    function(err, db) {
      if (err) {
        throw err;
      }
      console.log("Connection successful!");
      var dball = db.db("UserList");
      // Query the mailbox
      dball
        .collection("allUser")
        .find({
          email: search
        })
        .toArray(function(err, result) {
          if (err) {
            console.log(err);
            return;
          }

          function test() {// Apply promise execution, return true if the user is found, error if the user is found
            return new Promise((resolve, reject) = > {// If the user's mailbox does not exist and the verification code is correct, an error object is thrown otherwise
              if(! result.length && query[2].split("=") [1] === count) {
                resolve({
                  hasUser: false
                });
                // Store the data to the database
                dball.collection("allUser").insert(
                  [
                    {
                      email: query[0].split("=") [1].password: query[1].split("=") [1]}],function(err, result) {
                    if (err) {
                      console.log("Error:" + err);
                      return; }}); }else {// Throw an error object to the front end instead
                reject({
                  hasUser: true}); }}); } test() .then(data= > {
              console.log(data);
              res.send(data);
            })
            .catch(err= > {
              console.log(err); res.send(err); }); }); }); });// Login interface
app.get("/index/login".(req, res) = > {
  // Save the data from the front end
  let query = url.parse(req.url).query.split("&");
  MongoClient.connect(
    mongoDB,
    {
      useNewUrlParser: true
    },
    function(err, db) {
      if (err) {
        throw err;
      }
      console.log("Connection successful!");
      var dball = db.db("UserList");
      // Check whether the user exists
      dball
        .collection("allUser")
        .find({
          email: query[0].split("=") [1]
        })
        .toArray(function(err, result) {
          if (err) {
            console.log(err);
            return;
          }
          function test() {// If the user's mailbox and password match, an error object is thrown otherwise
            return new Promise((resolve, reject) = > {
              if (
                result.length &&
                result[0].password === query[1].split("=") [1]
              ) {
                resolve({
                  isUser: true
                });
              } else {
                reject({
                  isUser: false}); }}); } test() .then(data= > {
              console.log(data);
              res.send(data);
            })
            .catch(err= > {
              console.log(err); res.send(err); }); }); }); });// 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
  res.send(count);
});
// Listen to the service
app.listen(1024.() = > {
  console.log("Server Start~");
});
Copy the code

The mailbox js file (send-.js)

const nodemailer = require("nodemailer");
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: function(mail, content) {
    mailOptions = {
      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); }); }};module.exports = obj;
Copy the code