How to retrieve SessionID in NodeJS with multiple

2019-06-26 04:31发布

I'm new to NodeJS. I am developing a REST API and using express-session to deal with sessions. So, to get the session ID I'm using

var sessionID = req.sessionID

This sessionID is generated from the server side. So, when I scale up to two or more servers, this is a problem. For example, if one server shuts down and the request is redirected to another server (Assuming I have a load balancer), a new session ID is generated. So, is there a way to retrieve the session ID from the client side?

1条回答
我只想做你的唯一
2楼-- · 2019-06-26 05:01

Good question! Session management can be challenging to get up and running with - especially since to get up and running with any sort of sophisticated session management in node you need a ton of different packages, each with their own set of docs. Here is an example of how you can set up session management with MongoDB:

'use strict';

var express = require('express'),
  session = require('express-session'),
  cookieParser = require('cookie-parser'),
  mongoStore = require('connect-mongo')(session),
  mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/someDB');

var app = express();

var secret = 'shhh';

app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: secret,
  store: new mongoStore({
    mongooseConnection: mongoose.connection,
    collection: 'sessions' // default
  })
}));

// ROUTES, ETC.

var port = 3000;

app.listen(port, function() {
  console.log('listening on port ' + port + '.')
});

This configuration gives you access to req.sessionID but now it should persists across app servers if the user's session cookie has not expired.

I hope this works!

查看更多
登录 后发表回答