Nodejs Express4.x开发框架随手笔记

2020-06-17 07:44:45易采站长站整理

};
exports.doLogin=function(req,res){
var user = {
username:"admin",
password:"admin"
}
if(req.body.username==user.username && req.body.password==user.password){
res.redirect('/home');
}
res.redirect('/login');
};
exports.logout = function(req,res){
res.redirect('/');
};
exports.home = function(req,res){
var user = {
username:'admin',
password:'admin'
}
res.render('home',{title:'Home',user:user});
};

创建views/login.html和views/home.html两个文件

login.html


<% include header.html %>
<div class="container-fluid">
<form class="form-horizontal" method="post">
<fieldset>
<legend>用户登陆</legend>
<div class="control-group">
<label class="control-label" for="username">用户名</label>
<div class="controls">
<input type="text" class="input-xlarge" id="username" name="username">
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">密码</label>
<div class="controls">
<input type="password" class="input-xlarge" id="password" name="password">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">登陆</button>
</div>
</fieldset>
</form>
</div>
<% include footer.html %>
home.html:
<% include header.html %>
<h1>Welcome <%= user.username %>, 欢迎登陆!!</h1>
<a claa="btn" href="http://www.geedoo.info/logout">退出</a>
<% include footer.html %>

修改index.html,增加登陆链接

index.html


<% include header.html %>
<h1>Welcome to <%= title %></h1>
<p><a href="http://www.geedoo.info/login">登陆</a></p>
<% include footer.html %>

路由及页面我们都写好了,快去网站上试试吧。

7. Session使用

从刚来的例子上面看,执行exports.doLogin时,如果用户名和密码正确,我们使用redirect方法跳转到的home

res.redirect(‘/home’);

执行exports.home时,我们又用render渲染页面,并把user对象传给home.html页面

res.render(‘home’, { title: ‘Home’,user: user});

为什么不能在doLogin时,就把user对象赋值给session,每个页面就不再传值了。

session这个问题,其实是涉及到服务器的底层处理方式。

像Java的web服务器,是多线程调用模型。每用户请求会打开一个线程,每个线程在内容中维护着用户的状态。

像PHP的web服务器,是交行CGI的程序处理,CGI是无状态的,所以一般用cookie在客户的浏览器是维护用户的状态。但cookie在客户端维护的信息是不够的,所以CGI应用要模仿用户session,就需要在服务器端生成一个session文件存储起来,让原本无状态的CGI应用,通过中间文件的方式,达到session的效果。