我编写了以下测试代码来说明我的问题:
var express = require("express"),
MongoStore = require("connect-mongo")(express),
mongoose = require("mongoose"),
config = require(process.cwd() + "/src/config");
exports.run = function() {
console.info("running http server");
//create a new HTTP server
var server = express();
//sessions
server.use(express.cookieParser(config.sessions.secret));
server.use(express.session({
secret: config.sessions.secret,
key: config.sessions.key,
proxy: true,
cookie: {maxAge: config.sessions.maxAge, signed: true},
store: new MongoStore({
mongoose_connection: mongoose.connection
}, onStoreSetup)}));
//create a test ObjectID parameter
var testObjId = new mongoose.Types.ObjectId("522bb0205a259c636c000006");
server.get("/", function(req, res) {
if (req.session && req.session.testObjId) {
res.send("req.session.testObjId now has type " + typeof req.session.testObjId + " - WHY A STRING?");
}
else {
req.session.testObjId = testObjId;
req.session.save(function(err) {
if (err) throw err;
res.send("req.session.testObjId has type " + typeof req.session.testObjId + " - an Object, as expected - NOW REFRESH THIS PAGE");
});
}
});
//listen for incoming connections once session store is setup
function onStoreSetup() {
console.info("mongo session store connected");
server.listen(config.http.port);
console.info("http server listening on port %d", config.http.port);
}
};
首先,它将一个 ObjectId 类型的变量(来自 MongoDB 本机)写入服务器端会话存储。然后刷新页面时,使用了会话,参数的类型突然变成了字符串。
简而言之,如果您运行上述代码,将显示以下内容:
访问
/
回复:
req.session.testObjId has type object - NOW REFRESH THIS PAGE
/
再次访问回复:
req.session.testObjId now has type string - WHY A STRING?
为什么会变成字符串?