我有一个应用程序为每个用户创建 2 个会话。我已经找到了问题的根源,但我不完全理解它为什么会发生以及如何解决它。假设我像这样搭建一个示例应用程序:
compound init blah
cd blah
npm install
npm install connect-mongo
compound g c mytest
使config/environment.js看起来像这样:
module.exports = function (compound) {
var express = require('express');
var app = compound.app;
var secret = 'secret'; // Need this to check if there's been tampering with the session
var MongoStore = require('connect-mongo')(express);
app.sessionStore = new MongoStore({
url: 'mongodb://localhost/development'
});
app.cookieParser = express.cookieParser(secret);
app.configure(function() {
app.use(express.static(app.root + '/public', { maxAge: 86400000 }));
app.set('jsDirectory', '/javascripts/');
app.set('cssDirectory', '/stylesheets/');
app.set('cssEngine', 'stylus');
compound.loadConfigs(__dirname);
app.use(express.bodyParser());
app.use(app.cookieParser);
app.use(express.session({
secret: secret,
store: app.sessionStore,
cookie: {
maxAge: 86400000 // 24 hour session
}
}));
app.use(express.methodOverride());
app.use(app.router);
});
};
在app/controllers/mytests_controller.js文件中,将其修改为:
action('getMe', function(data) {
return send({success: true, data: 'got you!'});
});
action(function index(data) {
console.log(data.req.session); // has session data
var http = require('http');
var options = {
host: 'localhost',
port: 3000,
path: '/getMe'
};
//return send({success: true});
http.get(options, function(res) {
var data = '';
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', function() {
data = JSON.parse(data);
if (data) {
return send({success: true, data: data});
}
else {
return send({success: false, data: 'data is undefined'});
}
});
});
});
更新routes.js:
exports.routes = function (map) {
map.resources('mytests');
map.get('getMe', 'mytests#getMe');
// Generic routes. Add all your routes below this line
// feel free to remove generic routes
map.all(':controller/:action');
map.all(':controller/:action/:id');
};
当我导航到localhost:3000/mytests并打开 Mongo 数据库时,我看到创建了 2 个会话。如果我在索引中取消注释该返回,我只会创建 1 个会话,所以它显然是 http.get,但也许我误解了其他东西?谁能解释发生了什么?
理想情况下,我只希望我浏览到 /mytests 以进行会话,而不是它进行的任何后续调用。
注意:我意识到这个例子非常愚蠢,因为 /getMe 端点只返回了一些 JSON,但是在我的实际应用程序中,它做了更多的事情并进行了服务调用。
来自CompoundJS和Express Google Groups的交叉发布。