简体   繁体   中英

Node.js sessions

My greetings. I'd like to ask if it's possible to manage sessions in Node.js and how. I mean exactly Node.js, not express.

About app. I use static node server + websocket server, on front-end I have a simple SPA. And only one moment makes me think about sessions: when user refresh page he recieves new socket. So I have to tie up the "login status" with session, not socket.

Thanks.

Update: I've found the npm module "msession", this looks simple, and should do the job. But one problem now. I have to get the request and response objects from the socket.

The request I've managed to get this way:

let req = socket.upgradeReq;

I've tried this variant for response, but as expected, it didn't work:

let res = {writeHead: {}};

Any suggestions on response object?

也许这个插件将帮助您的node-session ,或者这一个node-client-sessions

Actually this blog-post made my day.

To conclude. Here's what I've recieved as result:

const http = require('http');
const staticServer = require('node-static');
const WebSocketServer = new require('ws');
const session = require('sesh/lib/core').magicSession();  

// WebSocket-server
const webSocketServer = new WebSocketServer.Server({port: 8081});

// Create a node-static server instance to serve the './public' folder
const fileFolder = new staticServer.Server('./public');

http.createServer(function (request, response) {            
  GLOBAL.session = request.session;
  request.addListener('end', function () {
    fileFolder.serve(request, response);
  }).resume();

}).listen(1337);

webSocketServer.on('connection', function(ws) {
  if( typeof(ws.session) === "undefined")
    ws.session = GLOBAL.session;
  /* Any logic here */
});

console.log("Static server created")

So, it's working sollution of the sockets based application, that has static file server and sessions. Maybe someone will find this usefull.

Sollution requires:

npm install --save node-static && npm install --save ws && npm install --save sesh

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