socket.io和express.js共享会话

时间:2016-12-17 04:26:59

标签: node.js express socket.io express-session

我遇到了这个解决方案,用于在socket.io和express.js之间共享会话: 这篇文章中的第二个答案(用户xpepermint): socket.io and express 4 sessions

不幸的是,由于变量io位于config/socketio.js而变量session位于config/express.js中,因此我不得不接受下面的代码:

io.use(function(socket, next) {
  session(socket.handshake, {}, next);
});

我在哪里放以及如何调整上面的代码?

我的app.js文件如下所示:

'use strict';

import express from 'express';
import mongoose from 'mongoose';
mongoose.Promise = require('bluebird');
import config from './config/environment';
import http from 'http';

// Connect to MongoDB
mongoose.connect(config.mongo.uri, config.mongo.options);
mongoose.connection.on('error', function(err) {
  console.error('MongoDB connection error: ' + err);
  process.exit(-1);
});

// Populate databases with sample data
if (config.seedDB) { require('./config/seed'); }

// Setup server
var app = express();
var server = http.createServer(app);
var socketio = require('socket.io')(server, {
  serveClient: config.env !== 'production',
  path: '/socket.io-client'
});

global.clients = [];
global.socketio = socketio; //added
require('./config/socketio').default(socketio);
require('./config/express').default(app);
require('./routes').default(app);

// Start server
function startServer() {
  app.angularFullstack = server.listen(config.port, config.ip, function() {
    console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
  });
}

setImmediate(startServer);

// Expose app
exports = module.exports = app;

0 个答案:

没有答案