初学node.js中实现删除用户路由
程序员文章站
2022-03-20 14:41:27
一、users_model.js 功能:定义用户对象模型
var mongoose=require('mongoose'),
schema=mongoose.s...
一、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> <link rel="stylesheet"type="text/css" href="/static/css/styles.css" rel="external nofollow" /> <script src="https://cdn.staticfile.org/angular.js/1.5.8/angular.min.js"></script> <script src="/static/js/my_app.js"></script> </head> <body> <div class="form-container" ng-controller="mycontroller"> <p class="form-header">用户修改</p> <form method="post" action="/user/update"> <label>用户名:</label> <input type="text" name="username" ng-model="user.username" disabled><br> <label>email:</label> <input type="email" name="email" ng-model="user.email"><br> <label>肤色:</label> <input type="text" name="color" 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);
五、页面显示效果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。