如何在具有多个服务器的NodeJS中检索SessionID? [英] How to retrieve SessionID in NodeJS with multiple servers?

查看:92
本文介绍了如何在具有多个服务器的NodeJS中检索SessionID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是NodeJS的新手.我正在开发REST API,并使用express-session处理会话.因此,要获取我正在使用的会话ID

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

此sessionID是从服务器端生成的.因此,当我扩展到两个或更多服务器时,这是一个问题.例如,如果一台服务器关闭并将请求重定向到另一台服务器(假设我有一个负载平衡器),则会生成一个新的会话ID.那么,有没有办法从客户端检索会话ID?

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?

推荐答案

好问题!会话管理的启动和运行可能具有挑战性-尤其是因为要在节点中使用任何种类的复杂会话管理启动和运行,您都需要大量不同的软件包,每个软件包都有自己的一套文档.以下是如何使用MongoDB设置会话管理的示例:

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 + '.')
});

通过此配置,您可以访问req.sessionID,但是现在,如果用户的会话cookie尚未过期,它应该在应用程序服务器之间仍然存在.

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.

我希望这行得通!

这篇关于如何在具有多个服务器的NodeJS中检索SessionID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆