在我的node.js应用中,我正在使用异步调用设置会话。我使用express-session进行会话管理。 但设置会话偶尔会出现。我使用角度应用调用2 node.js路由。
第一次调用HTTP get调用并正确获取所有数据。但只有最后延迟的路径数据才会被设置为会话。不是两条路线的数据。似乎设置来自延迟路由的数据正在替换快速路由会话数据。这是我的代码。
有时所有数据都设置为会话。 (2次浏览器刷新后)
var express = require('express');
var http = require('http');
var request = require('request');
var bodyParser = require('body-parser');
var session = require('express-session');
var ejs = require('ejs');
var cookieParser = require('cookie-parser'); // the session is stored in a cookie, so we use this to parse it
var app = express();
app.set('views', __dirname + '/views');
app.set('port', process.env.PORT || 8081);
app.use(express.static(__dirname + '/app/'));
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(cookieParser());
app.use(session({
secret: '232332dfdffd',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 3600000 }}))
app.engine('html', ejs.renderFile);
var server = app.listen(8081,function(){
});
app.get('/route1', function(req, res , next) {
var data1 = req.session.data1;
if(data1){
console.log("Session is not null. Getting data1 from session");
res.status(200);
res.send(data1);
}else{
request({
url: "testUrl",
qs: {},
json: req.body,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}, function(error, response, body){
if(error) {
console.log("error "+error);
res.sendStatus(error);
} else {
req.session.data1 = response;
res.status(response.statusCode);
res.send(response);
}
});
}
});
app.get('/route2', function(req, res , next) {
var data2 = req.session.data2;
if(data2){
console.log("Session is not null. Getting data2 from session");
res.status(200);
res.send(data1);
}else{
request({
url: "testUrl2",
qs: {},
json: req.body,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}, function(error, response, body){
if(error) {
console.log("error "+error);
res.sendStatus(error);
} else {
req.session.data2 = response;
res.status(response.statusCode);
res.send(response);
}
});
}
});