Modules and frameworks to be introduced: JQ, monogoDB, Mongoose, Express, Nodemailer, CORS, Multer, body-Parser.

The folder (roughly) structure is as follows:

CSS: home page style;

Get_pic: temporary file storage;

Img: default profile picture path.

Js: home page JS;

Main: entry server file (executed by the terminal);

Node_moudules: Modules and frameworks for download;

SavePic: Saves static files;

Set: registration, login, initial Mongoose, email sending and other modules;

Index: home page;

First, home page Html, Css, Js files:

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>
    <link rel="stylesheet" href="./css/main.css">
  </head>
  <body>
    <ul id="list">
      <li id="regChange">registered</li>
      <li id="loginChange">The login</li>
    </ul>
    <div id="reg">
      <input type="file" name="img" id="fileData">
      <button id="send">Upload the picture</button>
      <img id="headImg" src="">
      <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 src="./js/main.js"></script>
  </body>

</html>
Copy the code

Css

* {
    margin: 0;
    padding: 0;
  }
  div:nth-child(3) {
    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;
  }
  #send{
    display: inline-block;
    
  }
  #headImg{
    display: block;
    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;
  }
  table{
    margin: 50px auto 0;
  }
  td{
    text-align: center;
    border: 1px solid lightcoral;
  }
  td img{
    vertical-align: top;
  }
Copy the code

Js


// Home page js file


// Add listening events
btn.addEventListener("click", clickHandler); / / register
logbtn.addEventListener("click", clickHandler); / / login
email.addEventListener("click", sendHandler); // Send the verification code
regChange.addEventListener("click", changeHandler); // Toggle login registration
loginChange.addEventListener("click", changeHandler);
$('#send').on('click', sendHead);
webAdd = 'http://localhost:1024/main';
var table; // Create a successful login table

function sendHead(e) { // Upload the file
    var picData = new FormData(); // instantiate the file object
    picData.append("sendImg", $("#fileData") [0].files[0]); // Add the uploaded file to the file
    $.ajax({ // Upload to background in Ajax mode
        url: webAdd + '/head'.type: 'POST'.data: picData,
        cache: false.contentType: false.processData: false.success: function (data) {
            if(! data.error) { alert('Success');
                headImg.src = data.data; // Display the image on success
                headImg.style.width = '100px'; }},error: function () {
            alert('Error'); }}); }function clickHandler(e) {
    if (this.textContent === "Registered") {
        // Jump if empty
        if(! user.value || ! psd.value || ! sendmail.value) { alert("Input cannot be null.");
            return;
        }
        var AllData = {
            email: user.value,
            password: psd.value,
            mailnum: sendmail.value,
            headPic: headImg.src
        };
        // Click register to send email number, password, verification code, avatar to the background
        $.post(webAdd + '/reg', AllData,
            function (res) {
                If hasUser is true, the user name already exists. Otherwise, the user is successfully registered
                if (res.hasUser) {
                    // location.reload();
                    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
        $.post(webAdd + '/login', {
                email: loguser.value,
                password: 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");
                    login.style.display = "none";
                    list.style.display = 'none';
                    createTab(document.body, res.data[0]); // If login succeeds, create a user table
                } 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
    $.post(webAdd + '/sendmail', {
        email: 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"; }}function createTab(parent, data) {// Create a new table function
    if (table) {
        table.remove();// Delete the table if it exists
    }
    table = document.createElement('table');
    for (var str in data) {// Create a table based on traversal data
        var tr = document.createElement('tr');
        var td = document.createElement('td');
        if (str === 'head') {
            td.textContent = 'avatar:
            var img = new Image();
            img.src = data[str];
            td.appendChild(img);
        } else {
            td.textContent = str + ':' + data[str];
        }
        tr.appendChild(td);
        table.appendChild(tr);
    }

    parent.appendChild(table);
}
Copy the code

Then there are the other modules:

Mongoose Schema:

const mongoose = require('./main'); // Import main module
const Schema = mongoose.Schema; // Create a schema object
let userSchema = new Schema({
    email: {
        type: String.required: true
    },
    password: {
        type: String.required: true
    },
    head: {
        type: String.required: true}});// instantiate the object
let userModel = mongoose.model('allUser', userSchema); // Create a database
module.exports = userModel; // Throws the module
Copy the code

Mongoose database connection:

const mongoose = require('mongoose');/ / into the mongoose
mongoose.connect('mongodb://localhost:27017/UserList', {
    useNewUrlParser: true
});// Connect to the database
let db = mongoose.connection;
db.on("error".function (error) {
    console.log("Error:" + error);
});

db.on("open".function () {
    console.log("Connection successful");
});

db.on('disconnected'.function () {
    console.log('Disconnected');
});
module.exports = mongoose;// Throw the mongose object
Copy the code

Email verification module:

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,callback) {
    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); callback(); }); }};module.exports = obj;
Copy the code

Profile picture upload:

const express = require('express');
const router = express.Router(); // Create a route
var multer = require('multer'); // The file gets stored in the third party module
const fs = require('fs');
const path = require('path');
var upload = multer({
    dest: '.. /get_pic/'
}); // Create a temporary folder
router.post('/head', upload.single('sendImg'), (req, res) = > { // Routing address
    // Read the image of the transfer
    fs.readFile(req.file.path, (err, data) = > {
        if (err) {
            throw ('Load_Err');
        }
        let type = req.file.mimetype.split('/') [1]; // Get the file type name
        let name = new Date().getTime() + parseInt(Math.random() * Math.random() * 1000000); // Use a timestamp and a random number to generate a random name, and connect it to a complete filename
        // Save the file to the savePic folder
        let filename = name + '. ' + type;
        fs.writeFile(path.join(__dirname, '.. /savePic/' + filename), data, (err) = > {
            // Returns information to the front end
            if (err) {
                res.send({
                    err: 1.msg: 'Upload failed'
                });
                // Save the image and delete the temporary file
                fs.unlink(req.file.path, (err) = > {
                    if (err) {
                        console.log('Delete failed'); }});return;
            }
            res.send({
                err: 0.msg: 'Upload successful'.data: 'savePic/' + filename
            });
            // Save the image and delete the temporary file
            fs.unlink(req.file.path, (err) = > {
                if (err) {
                    console.log('Delete failed'); }}); }); }); });module.exports = router;
Copy the code

Registration:

const express = require('express');
const router = express.Router(); // Create a route
const Model = require('./mod'); // Pass in the database object
const fs = require('fs');
const path = require('path');
const sendMail = require('./send'); // The module object to which incoming messages are sent
var count = ""; // Create a null character to store the verification code, which can be called globally
// Use the POST method to transfer data
router.post('/reg'.(req, res) = > {
    // Save the data from the front end
    var mail = req.body.email;
    var psd = req.body.password;
    var mailnum = req.body.mailnum;
    var headUrl = req.body.headPic;
    // Connect to the database using the Model object
    Model.find({ // Query the mailbox
        'email': mail
    }).then((data) = > {
        // If the returned mailbox is found or the verification code is incorrect, an error will be thrown
        if (data.length >= 1|| mailnum ! == count) { res.send({hasUser: true
            });
            return;
        }
        res.send({
            hasUser: false
        });
        // If the image is uploaded, save the uploaded image, otherwise use the default image
        if (headUrl==='http://localhost:1024/') {
            headUrl = 'http://localhost:1024/img/cat.gif';
        }
        Model.insertMany({ // Insert the mailbox into the database instead
            'email': mail,
            'password': psd,
            'head':headUrl
        }).then((result) = > {
            console.log(result);
        })
    }).catch((err) = > {
        console.log(err);
    });
});

// Mailbox authentication interface
router.post("/sendmail".(req, res) = > {
    count = ""; // Initialize the captcha container
    var mail = req.body.email; // 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
    }
    var callback = () = > {
        console.log("Sent successfully");
    };
    sendMail.send(mail, count, callback); // Call the mail sending module
    res.send('send');
});

module.exports = router;
Copy the code

Login:

const express = require('express');
const router = express.Router();// Create a route
const Model = require('./mod');// Get the database object

router.post('/login'.(req, res) = > {// Routing address
    // Save the data from the front end
    var mail = req.body.email;
    var psd = req.body.password;
    Model.find({
        // Check whether the user exists. If the user's email address and password match, an error object will be thrown
        'email': mail,
        'password': psd
    }).then((data) = > {
        if (data.length >= 1) {
            res.send({
                isUser: true.data:data
            });
        } else {
            res.send({
                isUser: false
            });
        }
    }).catch((err) = > {
        console.log(err);
    });
});
module.exports = router;
Copy the code

The last server. Js

const express = require('express');
const app = express();
const cors = require("cors"); // Introduce cORS module (solve cross-domain problems)
const path = require('path');
var bodyParser = require('body-parser');

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
});
// Create a static file directory
app.use(express.static(path.join(__dirname, '.. /.. /user_info')));
// Solve the data format problem of POST transmission
app.use(bodyParser.urlencoded({
    extended: false
}))
app.use(bodyParser.json())
// Select import registration
const reg = require('.. /set/reg.js');
app.use('/main', reg);
// Route select import login
const login = require('.. /set/login.js');
app.use('/main', login);
// Select upload image module
const head = require('.. /set/sendhead.js');
app.use('/main', head);
// Enable listening
app.listen(1024.() = > {
    console.log('Server Start~');
});
Copy the code