接着之前,处理完注册的路由事件,后再做登录(查询):
//处理登录(查询)
app.post("/login", function(req, res){
console.log(req.body)//请求的参数对象
let {username, password: pwd} = req.body;
//检测用户名和密码是否正确
User.find({name: username}, function(err, doc){
console.log(doc);
if(err){return};
if(!doc.length){
res.json({
code: 1,
msg: "用户名错误!"
})
}else{
if(pwd === doc[0].pwd){
res.json({
code: 0,
msg: "登录成功!"
})
}else{
res.json({
code: 1,
msg: "密码错误!"
})
}
}
})
})
跳转评论页后。。。
在前端页面中确定用户正确登录后跳转至评论页,首先在页面中利用模板引擎渲染出数据库中所有评论数据,前端页面:
<script type="text/javascript">
var u = location.search.split("=")[1];
$(".username").text(u);
//渲染评论列表
var $list = $(".list");
$.get("/fetchComment", function(data){
if(!data.code && data.list.length){
var html = template("commentList", data);
$list.append(html).children("h2.empty").hide();
}
})
//删除
$list.on("click", ".btn-danger", function(){
$.post("/deleteComment", {_id: $(this).data("id")}, (data)=>{
if(!data.code){
$(this).parents("div.list-group").remove();
if(!$list.children("div.list-group").length){
$list.children("h2.empty").show();
}
}
})
})
</script>
后端的操作:
查询和指定数据删除(当然这里评论数据暂时是我在命令行中手动添加的):
当然在mongoose中操作数据库肯定要声明Schema,然后定义这个schema的model并在mainjs中引入:
schemas/comment.js
var mongoose = require("mongoose");
var comSchema = mongoose.Schema({
title: String,
content: String,
img: String,
author: String
});
module.exports = comSchema;
models/comment.js
var mongoose = require("mongoose");
var commentSchema = require("../schemas/comment");
var Comment = mongoose.model("comments", commentSchema);
module.exports = Comment;
main.js
//获取所有评论列表:
var Comment = require("./models/Comment");
app.get("/fetchComment", function(req, res){
var {title, content, img, author} = req.body;
Comment.find({}, function(err, doc){
if(err){return};
res.json({
code: 0,
list: doc
})
})
})
//删除指定某条评论:
app.post("/deleteComment", function(req, res){
Comment.findOneAndRemove({_id: req.body._id}, function(err, doc){
if(err){return};
res.json({
code: 0,
msg: "删除成功!"
})
})
})
版权声明:本文为qwe502763576原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。