事情是这样的,我在路由里获取用户信息然后通过req.session.userInfo = body;
进行设置。
可是会话设置是失败的。
为何?
router.get('/', function(req, res, next) {
var _id = req.query.UserID;
if (_id) {
fetch('https://github.com/')
.then(function(res) {
return res.text();
}).then(function(body) {
console.log(body);
});
res.render('index', { title: 'Express', UserName: 'nickname' });
}
});
fetch 是异步的行为吗?
如果是,你把render操作放在fetch外面是不行的。
代码里也没看见你用response.session 啊
==========修改=====================
既然fetch是异步的,那么
res.render('index', { title: 'Express', UserName: 'nickname' });
这句代码应该放在.then()
里面的。 改成下面这样试试
router.get('/', function(req, res, next) {
var _id = req.query.UserID;
if (_id) {
fetch('https://github.com/')
.then(function(res) {
return res.text();//这里结束了请求处理,下一个then就不能处理res了
}).then(function(body) {
res.session.user = body
res.render('index', { title: 'Express', UserName: 'nickname' });
});
}
});
我在console.log(body);
下面写了res.session.user = body
~贴上来的时候不知怎的没有。。。诡异。
fetch是异步的。
完整代码是这样的,可是还是不行~
router.get('/', function(req, res, next) {
var _id = req.query.UserID;
if (_id) {
fetch('https://github.com/')
.then(function(res) {
return res.text();
}).then(function(body) {
res.session.user = body
});
res.render('index', { title: 'Express', UserName: 'nickname' });
}
});