【发布时间】:2015-01-03 02:05:30
【问题描述】:
我有一个小问题。
我正在使用 MaxMind 获取用户所在的国家/地区,并以这种方式将国家/地区存储在 cookie 中:
exports.countryCookie = function(req, res, next) {
if (req.cookies.country === undefined) {
var ip = (req.header('X-Forwarded-For') || req.connection.remoteAddress).toString();
if (ip !== undefined) {
satelize.satelize({ip: ip}, function(err, geoData) {
if (err) return next();
res.cookie('country', geoData.country);
next();
});
} else {
next();
}
} else {
next();
}
};
我的家庭控制器:
exports.index = function(req, res) {
var country = req.cookies.country;
console.log(country);
if (country !== undefined) {
// do something...
} else {
// do something else...
}
}
路由:
app.get('/', myMiddleware.countryCookie, HomeController.index);
问题是:
第一次加载时console.log(country) 是undefined,但浏览器上设置了 Cookie...
刷新时不再是undefined。
如何在第一次加载页面时从 homeController 读取 cookie?
似乎中间件与 homeController 一起被触发,它错过了 cookie...
【问题讨论】: