在登陆注册当中引入 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:"服务器繁忙,请稍后重试[登录]"
})
}
})
- 当前文件目录