经过前面几次的学习,已经可以做下小功能,今天要实现的是修改用户路由。
一、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.updateUser=function(req,res){ User.findOne({_id:req.session.user}) .exec(function(err,user){ user.set(‘email‘,req.body.email); user.set(‘color‘,req.body.color); user.save(function(err){ if(err){ res.sessor.error=err; }else{ req.session.msg=‘User Updated. ‘; } res.redirect(‘/user‘); }); }); };
三、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" /> <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/update‘,users.updateUser);
五、页面显示效果
原文地址:https://www.cnblogs.com/zhouxuejia/p/10914258.html
时间: 2024-10-11 07:17:51