ユーザーごとに 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 グループからクロスポストされました。