初学node.js中实现删除用户路由

一、users_model.js 功能:定义用户对象模型

var mongoose=require('mongoose'), Schema=mongoose.Schema; var UserSchema=new Schema({ username:{type:String,unique:true}, email:String, color:String, hashed_password:String }); mongoose.model('User',UserSchema);

二、users_controller.js 功能:为Express服务器实现删除用户路由

var crypto=require('crypto'); var mongoose=require('mongoose'),User=mongoose.model('User'); function hashPW(pwd){ return crypto.createHash('sha256').update(pwd). digest('base64').toString(); } //实现删除用户路由 exports.deleteUser=function(req,res){ User.findOne({_id:req.session.user}) .exec(function(err,user){ if(user){ user.remove(function(err){ if(err){ req.session.msg=err; } req.session.destroy(function(){ res.redirect('/login'); }); }); }else{ req.session.msg="User Not Found!"; req.session.destroy(function(){ res.redirect('/login'); }); } }); };

三、user.html

<!DOCTYPE html> <html ng-app="myApp"> <head> <meta charset="UTF-8"> <title>用户修改</title> <linktype="text/css" href="https://www.jb51.net/static/css/styles.css" /> <script src="https://cdn.staticfile.org/angular.js/1.5.8/angular.min.js"></script> <script src="https://www.jb51.net/static/js/my_app.js"></script> </head> <body> <div ng-controller="myController"> <p>用户修改</p> <form method="POST" action="/user/update"> <label>用户名:</label> <input type="text" ng-model="user.username" disabled><br> <label>Email:</label> <input type="email" ng-model="user.email"><br> <label>肤色:</label> <input type="text" ng-model="user.color"><br> <input type="submit" value="Save"> </form> </div> <form method="POST" action="/user/delete"> <input type="submit" value="删除用户"> </form> <hr><%=msg%> <hr>{{error}} </body> </html>

四、routes.js 功能:为Express服务器实现处理Web请求路由

var crypto=require('crypto'); var express=require('express'); module.exports=function(app){ var users=require('./controllers/users_controller'); app.use('/static',express.static('./static')). use('/lib',express.static('../lib') ); app.post('/user/delete',users.deleteUser);

五、页面显示效果

初学node.js中实现删除用户路由

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/19c8a8d6ce8a9f7c369bc5ad2c6fe2de.html