0

使用 ExpressJs 4 和 Primus,我可以共享 Express 会话。

primus.on('connection', function (spark) {
  var req = spark.request; // Here, I have the Express session
  req.session.foo = 'bar'; // I try to write into the session.
});

当我将{ foo: 'bar' }值写入会话时,我无法从标准的 http express 调用中检索它。

app.get('/api/...', function (req, res) {
  console.log(req.session.foo); // Print undefined :'(
  res.send();
});

输出是undefined。你能解释一下为什么吗?谢谢。

4

2 回答 2

3

根据 express-session 文档,我们可以将 session 保存到 store。 https://github.com/expressjs/session#sessionsave

primus.on('connection', function (spark) {
  var req = spark.request; // Here, I have the Express session
  req.session.foo = 'bar'; // I try to write into the session.
  req.session.save(); // Save the session to the store
});

然后,效果很好!

于 2014-09-05T09:38:04.790 回答
1

这是我目前的工作方式(Express 4.13.4;Primus 4.0.5)

应用程序.js

var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');

var sockjs = require('sockjs');
var http = require('http');
var Primus = require('primus');
var realtime_functions = require('./custom_modules/realtime_functions.js');

var app = express();

var app_secret_key = 'app secret';
var cookieparser = cookieParser(app_secret_key);
var sessionstore = new session.MemoryStore();

app.use(cookieparser);
app.use(session({
  secret: app_secret_key,
  saveUninitialized: false,
  resave: false,
  store: sessionstore
}));

realtime_functions(app, cookieparser, sessionstore);

realtime_functions.js

var primus_start = function(express, cookies, store) {

  var server = http.createServer(express);

  var primus = new Primus(server, {transformer: 'SockJS', parser: 'JSON'})
  primus.use('rooms', primusRooms)
  server.listen(3000, '0.0.0.0');

  primus.before('cookies', cookies);
  primus.before('session', function session(req, res, next) {
    try {
      var sid = req.signedCookies['connect.sid'];
      if (!sid) { return next(); }
      req.pause();
      store.get(sid, function (err, session) {
        if (err) {
          primus.emit('log', 'error', err);
          return next();
        }
        if(session) {
          req.sessionID = sid;
          req.sessionStore = store;
          req.thesession = store.createSession(req, session);
        }
        req.resume();
        next();
      });
    } catch(error) {
      console.log(error);
    }
  });

  primus.on('connection', function(spark) {
    spark.on('data', function(data) {
      spark.request.thesession.addthis = "save this to session";
      spark.request.thesession.save();
    });
  });
}
module.exports = primus_start;
于 2016-02-27T18:38:16.523 回答