在登陸注冊當中引入 ejs
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/school",{
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.once("open",err=>{
if(err){
console.log(err);
return;
}
console.log("database connection success!");
})
const mongoose = require("mongoose");
const studentSchema = mongoose.Schema({
username:{
type:String,
unique:true,
require:true
},
password:{
type:String,
require:true
}
})
const studentSch = mongoose.model("students",studentSchema);
module.exports = studentSch;
const express = require("express");
const app = express();
app.listen(8080);
//引入path
const path = require("path");
//引入ejs
app.set("view engine","ejs");
app.set("views","views");
//連接數據庫
require("./db/db")
//獲取數據庫映射表
const studentSchema = require("./model/students");
//使用內置中間件加載靜態資源
app.use(express.static("./public"));
//錯誤的頁面路徑
const errPath = path.resolve(__dirname,"./public/err.ejs");
/**
* 注冊路由
*/
app.get("/register",async (req,res)=>{
console.log(req.query);
const {username,password} = req.query;
//校驗注冊的信息是否為空!
console.log(errPath);
if(!username || !password){
return res.render(errPath,{
errData:"當前注冊賬號或密碼不能為空!"
})
}
//校驗用戶賬號是否已經存在
const isHasUser = await studentSchema.findOne({
// username:username
username
})
if(isHasUser){
return res.render(errPath,{
errData:"當前注冊賬號已存在"
})
}
//正則校驗賬號密碼
const reg = /^[0-9a-zA-Z_]{6,16}$/;
if(!reg.test(username || !reg.test(password))){
return res.render(errPath,{
errData:"當前注冊賬號或密碼格式不正確!"
})
}
//進行注冊處理
try {
await studentSchema.create(req.query);
res.redirect("/login.html")
} catch (error) {
return res.render(errPath,{
errData:"服務器繁忙,請稍后重試[注冊]"
})
}
})
app.get("/login",async (req,res)=>{
const {username,password} = req.query;
//非空校驗
if(!username || !password){
res.render(errPath,{
errData:"當前登錄的賬號或密碼不能為空!"
})
}
//正則判斷
const reg = /^[0-9a-zA-Z_]{6,16}$/;
if(!reg.test(username || !reg.test(password))){
return res.render(errPath,{
errData:"當前登錄賬號或密碼格式不正確!"
})
}
//驗證賬號是否存在
const isHasUser = studentSchema.findOne({
username
})
if(!isHasUser){
return res.render(errPath,{
errData:"當前來登錄的賬號不存在"
})
}
//進行登錄處理,登錄完畢之后跳轉到主頁
const checkLoin = await studentSchema.findOne(req.query);
if(checkLoin){
res.redirect("/index.html");
}else{
res.render(errPath,{
errData:"服務器繁忙,請稍后重試[登錄]"
})
}
})
- 當前文件目錄
