经过前面几次的学习,已经可以做下小功能,今天要实现的事用户登录路由。
一、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.login=function (req,res){ User.findOne({username:req.body.username}) .exec(function(err,user){ if(!user){ err='User Not Found'; }else if(user.hashed_password===hashPW(req.body.password.toString())){ req.session.regenerate(function(){ req.session.user=user.id; req.session.username=user.username; req.session.msg='Authenticated as ' +user.username; res.redirect('/'); }); }else{ err='Authentication failed. '; } if(err){ req.session.regenerate(function(){ req.session.msg=err; res.redirect('/login'); }); } }); };
三、login.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> <input type="submit" value="登录"> </form> </div> <a href="/signup" rel="external nofollow" >注册</a> <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('/login',function(req,res){ if(req.session.user){ res.redirect('/'); } res.render('login',{msg:req.session.msg}) }); app.post('/login',users.login);
页面效果
以上所述是小编给大家介绍的nodejs中实现用户登录路由功能,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!