connect中间件session、cookie的使用方法分享_node.js

WBOY
Release: 2016-05-16 16:44:02
Original
1741 people have browsed it

Connect是一个node中间件(middleware)框架。具体不表,看官网介绍 http://www.senchalabs.org/connect/

在app.js中配置下(必须放到app.use(routes);之前)

复制代码代码如下:

var connect = require("connect");
app.use(connect.cookieParser());
app.use(connect.session({ secret: 'jiami', cookie: { maxAge: 60*60*24*1000}}));

然后在控制器中使用

复制代码代码如下:

//设置
req.session.username="sess_username";
req.session.password="sess_admin";
req.session.your = {username:"sess_name",password:"sess_pwd"};
//使用
console.log(req.session.username);
console.log(req.session.your);

其它方法

复制代码代码如下:

//注销session
req.session.destroy(function(err){
console.log(err);
})
//重新生成sid
req.session.regenerate(function(err){
console.log(err);
});

当设置了session后,我们看到cookie中多了条sid,是为了记录会话ID的

打印req.cookies和req.session对象

复制代码代码如下:

console.log(req.cookies);
console.log(req.session);

可以看到session是通过存了个connect.sid的方式来与客户端会话的,不过session是存在内存中的

二、cookie,官方文档:(http://www.senchalabs.org/connect/cookieParser.html 这个文档坑了我整整一天时间),费话不表,下面的例子是哥试出来的,因为文档上没写使用方法

设置

复制代码代码如下:

//设置cookie
res.cookie("user",{username:"cookie_name",password:"cookie_pwd"},{ maxAge: 60*60*24*1000,httpOnly:true, path:'/'});
res.cookie("msg", "用户名或密码不能为空", {maxAge:60*60*24*1000});

删除

复制代码代码如下:

res.cookie("msg", "用户名或密码不能为空", {maxAge:0});

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!