Realize the goal: the default start page is the login page, enter the account password, if you do not have this account, then jump to the registration page, and enter the personal page after successful registration. When logging in, if the account password does not match, then jump to the error page, and jump to the login page after three seconds.
We also need to ensure that if the user is not logged in, then they cannot enter the personal page (via url). Simple use of express mongoDB.
Realize the effect diagram:
At this time, there is no data in the database, so the matching will not succeed, and it will jump Go to the registration page.
Click to register, then you will jump to the personal page.
personal page welcome user
There is an additional user admin in the database
The username is set in the browser cookie
Suppose we delete the cookie, what will be posted when we enter main.html (personal page). Yes, it will jump to the login page.
I think you probably know how to do it.
When logging in, we use the username and password returned by the front end to query the database. If the match is successful, set the username of the cookie, and then jump to the personal page. If there is no such account, then jump to the registration page. If the match fails, then it will jump to failure page
When registering, after the registration is successful, we will set a cookie and then jump to the personal page (note that we have not tested the uniqueness of the account here)
Take a look at the structure of the demo
model’s index, js puts the model used by mongoDB, views puts some template html (processed by express template engine) index.js is the entry
First look at index.js
const express = require("express"); const path = require("path"); const bodyParser = require("body-parser"); const getModel = require("./model"); const crypto = require("crypto"); const cookieParser = require("cookie-parser"); const app = express(); app.set("views", path.join(__dirname, "views")); app.set("view engine", "html"); app.engine("html", require("ejs").__express); app.use(bodyParser.urlencoded({ extended: true })); //Used to parse post parameters app.use(cookieParser()); const User = getModel("User"); //get the model function isLogin(req, res, next) { //A middleware that detects the username attribute on the cookie. If there is, it proves that the login was successful. Whether it is jumping to the login page const { username } = req. cookies; if (username) { //if exists next(); } else { res.redirect("/login"); } } app.get("/login", function (req, res) { //login res.render("login"); }) app. post("/login", function (req, res) { let { username, password } = req. body; password = crypto.createHmac("md5", "cyl").update(password).digest("hex"); //Add salt and then encrypt (accurately it should be digest) User. findOne({ username}, function (err, doc) { if (err) { // Handle errors } if (doc) { //Query the database and find that it exists, then go to the personal page if (doc.password === password) { //if the password also matches res.cookie("username", username); res.redirect("/main"); res.end(); } else { res.render("error"); } } else { res.redirect("/register"); //If it does not exist, go to the registration page } }) }) app. get("/register", function (req, res) { res. render("register"); }) app. post("/register", function (req, res) { let { username, password } = req. body; password = crypto.createHmac("md5", "cyl").update(password).digest("hex"); User. create({ username, password }, function (err, doc) { if (err) {// error handling } //Currently there is no requirement for the uniqueness of the account number if (doc) { //registration is successful res.cookie("username", username); res.redirect("/main"); res.end(); } }) }) app.get("/main", isLogin, function (req, res) { //Check whether you have logged in through the isLogin middleware const { username } = req. cookies; res. render("main", { username }) }) app. get("/", isLogin, function (req, res) { res. redirect("login") }) app.listen(8080, () => { console.log("http://localhost:8080 has been opened") });
The first is to introduce some modules, then the template engine settings of express, and then introduce the middleware for processing post request parameters and cookies, and then the model for obtaining the database
The isLogin middleware is what we use to judge whether to log in (use it in get(“/main”) get(“/”) and then the following is the route
a few simple html
error.html
<!DOCTYPE html> <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>Error Page</title> </head> <body> <p>Sorry, the username or password was entered incorrectly! After 3 seconds, the page jumps to the login page</p> </body> <script> window.onload = () => { setTimeout(() => { window.location.href = "http://localhost:8080"; }, 3000) } </script> </html>
login.html
<!DOCTYPE html> <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>Login Page</title> </head> <body> <h1>Login page</h1> <form method="POST" action="/login"> <label for="name">User name:</label><input id="name" type="text" name="username" /> <label for="pw">Password:</label><input id="pw" type="password" name="password" /> <input type="submit" value="login"/> </form> </body> </html>
<!DOCTYPE html> <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>Registration Page</title> </head> <body> <h1>Registration page</h1> <form method="POST" action="/register"> <label for="name">User name:</label><input id="name" type="text" name="username" /> <label for="pw">Password:</label><input id="pw" type="password" name="password" /> <input type="submit" value="register"/> </form> </body> </html>
register.html
main.html
<!DOCTYPE html> <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>Personal Page</title> </head> <body> <h1>Welcome <%= username %></h1> </body> </html>
Then look at mode/index.js
const mongoose = require("mongoose"); const conn = mongoose.createConnection("mongodb://localhost/test"); //Connect to the database const UserSchema = new mongoose.Schema({ //Set Schema username: { //username type: String, required: true }, password: { //password type: String, required: true }, rTime: { //Registration time type: Number, default: Date.now() } }) const User = conn.model("User", UserSchema); const model = { User }; module. exports = function (modelName) { return model[modelName]; }
Note that what I return is a function to get the response model by giving modelName
To understand the code, you need to understand the basic use of express, routing, middleware, template engine, etc., the use of mongoose, cookies, etc.