简体   繁体   中英

Sessions in Node.JS

I'm very new to Node.JS and I can't seem to find a way to store Sessions, or at least not a official way.

I read you can do it with redis I found that express has it's own Session handler and I found a git

Now I don't know which method to use... I'm from a PHP background where it was really easy to do this.

Any help is appreciated!

I would prefer not to install any more modules, I am currently using Express so if someone can send me a detailed guide to Express's session handler I'll really appreciate it!

Check out this article.

NODE.JS AND EXPRESS - SESSIONS

It even covers method to persistent data with redis and MongoDB.

First of all, you need to use the proper middleware or include it when you are setting up your express app.

app.use(express.cookieParser());
app.use(express.session({secret: 'this is the secret'}));  

or

express --sessions myapp  

both the cookieParser and sessions middleware are required also, the order matters.
After you include the required middleware, a sessions object is added to every request and you can set and get properties on the object.

setting:

app.get('/', function(req, res) {
  req.session.user = 'mike';
  res.send('index');
});

getting:

app.get('/about', function(req, res) {
  var user = req.session.user;
  res.send("I know you, you're" + user + '!');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM