我遇到了这个解决方案,用于在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;