时间:2021-01-19 12:05:37 | 栏目:NodeJS | 点击:次
经过前面几次的学习,已经可以做下小功能,今天要实现的是用户注册路由。
一、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.signup=function(req,res){ var user=new User({username:req.body.username}); user.set('hashed_password',hashPW(req.body.password)); user.set('email',req.body.email); user.save(function(err){ if(err){ res.session.error=err; res.redirect('/signup'); }else{ req.session.user=user.id; req.session.username=user.username; req.session.msg='Authenticated as '+user.username; res.redirect('/'); } }); };
三、signup.html 用户注册页面
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>用户注册</title> <link rel="stylesheet"type="text/css" href="/static/css/styles.css" rel="external nofollow" /> </head> <body> <div class="form-container"> <p class="form-header">注册</p> <form method="POST" > <label>用户名:</label> <input type="text" name="username"><br> <label>密码:</label> <input type="password" name="password"><br> <label>Email:</label> <input type="email" name="email"><br> <input type="submit" value="注册"> </form> </div> <hr> <%=msg %> </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.get('/signup',function(req,res){ if(req.session.user){ res.redirect('/'); } res.render('signup',{msg:req.session.msg}) }); app.post('/signup',users.signup);
页面效果
数据库显示
总结