首先呢这是一篇翻译或来的文章,文章内容讲的很详实,比国内文章强一些。英语水平有限,错误之处还需订正,希望对大家有些帮助,
Using sessions to keep track of users as they journey through your site is key to any respectable application. Luckily, as usual, using Express with your Node.js application makes it super simple to get sessions
up and running.
使用Session是我们在追踪用户在他们使用应用程序的时候我们能够准确掌握其操作的关键。幸运的是,像往常一样,在Node.js之中套用框架Express(点击打开链接)能够让我们超级简单的操作Session和运行程序。
Express App
Before we do anything else, we need an Express application. Creating an Express app is extremely simple, and the makers of Express do a pretty good job documenting the process.
在我们做任何事情之前,我们需要一个Express的应用程序。创建一个express应用程序是极其简单的。而且Express框架的作者为该框架已经为我们学习该框架准备了丰富的文档和学习指南,一下是Express的一个示例:
package.json
{
"name": "SessionsExample",
"version": "0.0.1",
"dependencies": {
"express": "3.x"
}
}
app.js
var express = require('express');
var app = express();
app.get('/awesome', function(req, res) {
res.send("You're Awesome.");
});
app.get('/radical', function(req, res) {
res.send('What a radical visit!');
});
app.get('/tubular', function(req, res) {
res.send('Are you a surfer?');
});
app.listen(process.env.PORT || 8080);
Now we have three routes defined and available to visit. If you visit one page, it's like you are visiting it for the first time. However, what if we wanted to remember the last page someone visited? We can easily do that with sessions.
现在我们已经定义了三个路由并能够访问,假如你想访问其中一个页面,就像其他第一次访问页面一样。然而,我们想记住最后一次访问的页面该怎么办?我们可以使用Session很简单的解决该问题。
Remembering Things
Before we dive in, there is a little bit of setup necessary. We need to “use” the cookie parser and the session features of express before the sessions will be made available. You do this before you define any routes, which in our case would look like so:
在我们使用Session时,我们需要做一些必须的工作,我们需要使用"use"方法去定义中间件cookieParser和Sesion遮掩才能正确使用Express提供的Session功能。你必须在你定义路由之前做那些工作。下面使我们写完成的例子:
app.js
var express = require('express');
var app = express();
app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));
app.get('/awesome', function(req, res) {
res.send('Your Awesome.');
});
app.get('/radical', function(req, res) {
res.send('What a radical visit!');
});
app.get('/tubular', function(req, res) {
res.send('Are you a surfer?');
});
app.listen(process.env.PORT || 8080);
Since sessions use cookies to keep track users we need both the cookie parser and the session framework. It is important to note that the cookie parser is used before the session, this order is required for sessions to work.
既然sessions使用cookies去追踪用户,那这样我们需要cookieparser和session框架,这非常重要在我们使用session让其工作之前要先去定义cookieparser。
We also provide a secret to the session initializer, which provides a little more security for our session data. Of course you might what to use a key that is a little more secure.
我们也提供了一个加密秘钥在我们session初始化的时候,让其为我们的session数据提供一些安全,当然,你也可以使用一个秘钥来保证一定的安全性。
Sessions are accessible through the request object in each route. You can get and set properties just like you would when handling an object normally. For example, lets set some session data in the awesome route.
Session是可以在每一个路由请求通过request对象能够轻易地获取。你能够像你处理普通对象那样来获取和设置session里面的属性内容。
例如,让我们在“/awesome”的路由请求中设置一些session数据
app.get('/awesome', function(req, res) {
req.session.lastPage = '/awesome';
res.send('Your Awesome.');
});
It really is as easy as accessing the session object in the request. Let’s say we want to print the last page the user visited as well.
app.get('/awesome', function(req, res) {
if(req.session.lastPage) {
res.write('Last page was: ' + req.session.lastPage + '. ');
}
req.session.lastPage = '/awesome';
res.send('Your Awesome.');
});
Lastly we can apply this to the rest of the routes.
var express = require('express');
var app = express();
app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));
app.get('/awesome', function(req, res) {
if(req.session.lastPage) {
res.write('Last page was: ' + req.session.lastPage + '. ');
}
req.session.lastPage = '/awesome';
res.send('Your Awesome.');
});
app.get('/radical', function(req, res) {
if(req.session.lastPage) {
res.write('Last page was: ' + req.session.lastPage + '. ');
}
req.session.lastPage = '/radical';
res.send('What a radical visit!');
});
app.get('/tubular', function(req, res) {
if(req.session.lastPage) {
res.write('Last page was: ' + req.session.lastPage + '. ');
}
req.session.lastPage = '/tubular';
res.send('Are you a surfer?');
});
app.listen(process.env.PORT || 8080);
And there it is, a session enabled application.
ok,就是这样,一个session可用的应用程序
Using Redis
There is only one major issue with our sessions. Anytime we restart our app, all of the user sessions are lost. I think we can all agree this
presentsa problem with our updating process.
现在只有一个很严重的问题。那就是无论何时我们重启程序,所有用户的session数据都会丢失,我认为我们完全认同在进步过程中这个目前的难题。
There are several ways around this problem, but one of the best ways is to use an external store for the session data. More
specifically, we can use a Redis store. This way the session data is completely separate from our running application.
关于这个难题有好几种解决方式,但是其中最好的一个方式是为session数据使用扩展的存储方式。更好的方式是,我们可以使用一个Redis 存储,使用这种方式我们完全可以将session数据存储和应用程序本身分割开来,而不依赖与浏览器等宿主环境。
To set up Redis with Express sessions, we need an extra module. This module is the Redis client used by connect and helps create a streamlined solution for connecting Redis to Express. First we have to make sure its in our package.json.
为了在Express session中设置Redius,我们需要额外的模块,这个模块是通过Redis客户端进行联系的而且帮助创建一个为连接Redis和Express的最新型的解决方案。首先第一格我们需要设置一下我们的package.json文件
package.json
{
"name": "SessionsExample",
"version": "0.0.1",
"dependencies": {
"express": "3.x",
"connect-redis": "1.4.x"
}
}
Then we have to require it.(包含进来文件)
var express = require('express');
var app = express();
var RedisStore = require('connect-redis')(express);
app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));
Notice that we pass Express to the Redis connector. This is required for Express and the Redis store to play nice with each other, which makes the process a whole lot easier later.
注意我们传递了Express对象给了Redis 连接。这是为了使Express和Redis两者能够后互相协调的工作,这个使得整个过程更加的容易。
In order to set up the Redis store with our sessions, we are going to modify our app.use call. The session initializer not only takes a secret, but a store as well. As you can probably guess, this is used to tell the session manager where to put all the session
data. All we have to do is pass in an object it can use instead of its native storage.
为了建立Redis来存储我们的session。我们需要改变我们的调用方式。这个session初始化不仅仅是设置一个secret,而且也是初始化了存储模块。这样你可能才想到,这个是用来告诉session管理模块应该把这些session数据存放在哪个地方。仅需要我们所做的是传递一个对象来代替我们本地存储
var express = require('express');
var app = express();
var RedisStore = require('connect-redis')(express);
app.use(express.cookieParser());
app.use(express.session({
store: new RedisStore({
host: 'localhost',
port: 6379,
db: 2,
pass: 'RedisPASS'
}),
secret: '1234567890QWERTY'
}));
It’s as simple as that. The RedisStore constructor can take all the normal options you would expect. In this case we are going to use database 2 with the password we use to authenticate with our Redis instance.
看起来如此简单。这个RedisStore构造函数可以设置所有的你所希望设置的值。在这种情况下,我们可以我们可以使用数据库2并捎带着权限的密码在我们的Redis实例中。
Now all of our session data will stored safely in our Redis database. This also means that any time we restart our node application, the session data is immune from being reset because it is not stored under the same process as our application.
现在所有的我们的session数据可以安全的存储在Redis数据库里,这个也意味着我们可以在任何时候启动我们的node应用程序是的时候,这些session数据也不会被重置。这是因为他没有被存储在我们的程序进程之中。
What about Mongo?
So some of you out there might be wondering if you can use MongoDB to store your session data. Well, using Mongo in place of Redis in our previous example is actually just as simple as using Redis. Instead ofconnect-redisyou
just use, you guessed it,connect-mongo.
这里面的我们很多会为什么不用M哦你goDB来存储我们的session数据,好吧,使用Mongo来代替Redis是我们的上一个例子其结果两者是一样的简单,两者使用可以根据需要来选择。
package.json
{
"name" : "SessionsExample",
"version" : "0.0.1",
"dependencies" : {
"express" : "3.x",
"connect-mongo" : "0.3.x"
}
}
Just add a few “Mongo”s where you see “Redis” and it all falls into place.
var express = require('express');
var app = express();
var MongoStore = require('connect-mongo')(express);
app.use(express.cookieParser());
app.use(express.session({
store: new MongoStore({
url: 'mongodb://root:myPassword@mongo.onmodulus.net:27017/3xam9l3'
}),
secret: '1234567890QWERTY'
}));
It is honestly that simple. Of course there area
lot moreoptions you have when creating your MongoStore instance, but the example above gets you the basic functionality and will start storing your session data in your Mongo database.
So there are the basics behind Express sessions. As you can see, it is not complicated, and just requires a little setup to get rolling. Don’t forget, if you have any questions or comments, throw them out below.
We are never afraid of feedback.
分享到:
相关推荐
安装通过npm添加到您的应用npm : npm install express-mysql-session --save 这将安装express-mysql-session并将其添加到应用程序的package.json文件中。重要笔记这里有潜在的陷阱和其他重要信息。旧版本对于仍在...
express-session - 会话集成 express-winston - winston 进入 express,将所有请求记录到文件中。 mongoose - mongoDB 数据访问 护照 - 认证和授权 护照本地 - 表单身份验证模块 温斯顿 - 伐木
helenshop-comm 服务器端渲染的电子商务应用程序,用于查看,编辑和购买各种产品。 用户可以创建一个帐户以将其产品添加到商店,尽管使用匿名购物车开始购物无需任何帐户。...Express-Session和Express
所需的节点模块: const CryptoJS = require('crypto-js') const express = require('express') const session = require('express-session') const https = require('https') const request = require('request') ...
本文实例讲述了nodejs使用express获取get和post传值及session验证的方法。分享给大家供大家参考,具体如下: 获取get和post传值 ...var session = require('express-session'); var cookieParser = require
文件夹模块和技术实用程序生产后端Nodejs 猫鼬加密斯瓦格头盔Express et Express-Session等Express-Flash 身体解析器模块和技术应用开发工具BACK-END Nodejs 猫鼬加密斯瓦格头盔Express et Express-Session等Express...
一个nodejs、express、mysql、redis、jwt、session、crypto-js写的后台模板,提供初学者学习,详细的模块划分 src/ authentication 鉴权模块操作 common 公共资源模块操作处理 connect 数据库链接模块 public 静态...
使用NodeJs的express框架完成电影网站后端搭建; 使用mongodb完成数据存储,通过mongoose模块完成对mongodb数据的构建; 使用jade模板引擎完成页面创建渲染; 使用Moment.js格式化电影存储时间; 3、本地开发环境...
使用MySQL+ExpressJS+AngularJS+NodeJS尝试开发的图书管理系统,开发前端后台模块,后台用ExpressJS和NodeJS搭建...ExpressJS用到了:body-parser,cookie-parser,cookie-session,ejs,express-session,MD5加密等模块
节点快速会话 显示会话如何在 nodejs 中工作的示例。 这里用到了Body parser、Cookie Parser、Cookie Session和express模块。
nodejs 简介与安装 全局对象与常用工具 http协议 node_Http_Server buffer fs_模块 模块系统 mongoDB_mongooose express 工程 cookie_session 部署_远程服务器
N-blog 使用 Express + MongoDB ...npm i config-lite connect-flash connect-mongo ejs express express-formidable express-session marked moment mongolass objectid-to-timestamp sha1 winston express-winston -
nodejs_authentication 在 Node.js 中使用用户身份验证的简单 CRUD 工具:"bcrypt": "^0.8.0" "body-parser": "^1.10.0" "connect-flash": "^0.1.1" "cookie-session": "^1.1.0" "ejs": "^1.0.0" "express": "^...
**express-session**: 用于设置客户端cookie以验证登录状态和用户权限,对于不同用户只能删除自己发表的评论,只有管理员可以发表文章和操作所有评论。 **ejs**: 用于使用页面模板,以适配各种界面排布,便于每次...
express-session mysql BootStrap 系统在生活中的应用十分广泛,无论是个人还是企业,在日常生活中都需要系统,不仅可以提高工作效率和质量,也可以提高数据准确性,以下是系统的好处: 1. 提高效率:系统可以自动化...
cookie会话 简单的基于cookie的会话中间件。 用户会话可以用cookie的两种主要方式存储:在服务器上或在客户端上。... cookie-session可用于存储“轻量”会话,并包含一个标识符以查找数据库支持的辅助存储
一、express简介1.1 概念基于 Node.js 平台,快速、开放、极简的 web 开发框架1.2 特点node:异步、事件驱动、单线程、语言统一、适用I/O密集型高并发express:更简洁的API、中间件、和路由让程序的组织管理变的更加...
nodejs 带有nodejs,express等的gugutech联系人项目的前端框架###初始框架构建建立快递框架express gugutech_campus_nodejscd gugutech_campus_nodejsnpm intall 安装基本模块npm install hiredis redis express-...
LoginApp 使用Nodejs,passport和Mongodb的LoginApp 使用以下在package.json中定义的节点模块“ bcryptjs”:“ ”,//密码哈希“ body-parser”:“ ”,// Parse JSON“ connect-flash”:“ ”,// Flash消息“ ...
var session = require ( 'express-session' ) 会话(选项) 使用给定的options创建会话中间件。 注意会话数据不会保存在cookie本身中,而只会保存会话ID。 会话数据存储在服务器端。 注意从1.5.0版本开始,该...