【发布时间】:2020-01-04 18:56:44
【问题描述】:
我有 2 个应用程序,WEB 和 APP,它们托管在不同的端口(本地)和不同的域(公共)上,例如:
- www.domain.com (WEB)
- app.domain.com (APP)
我正在尝试在两个应用程序上调用相同的登录会话,我的代码在我的本地机器上运行良好(可能是因为它相同的主机名和端口不会中断会话并将其计为新会话)
当我尝试将我的代码推送到生产环境时,它根本不起作用,网络会话无法识别 APP 设置的会话
APP 是设置会话的地方(它处理登录)。
下面的 session 和 cors 代码用于 web 和 app
const cors = require('cors')
app.use(cors());
app.use(cookieParser());
app.use(
session({
resave: true,
saveUninitialized: true,
secret: process.env.SESSION_SECRET,
cookie: { maxAge: 1209600000 }, // two weeks in milliseconds
store: new MongoStore({
mongooseConnection: mongoose.connection,
autoReconnect: true
})
})
);
一旦用户从 APP 登录,我希望通过 WEB 包维护和调用该会话。这样我也可以动态改变网站体验。
解决方案
@theusguy 关于添加域参数是正确的。还有很多问题需要解决
Headers.Host 我的 nginx 配置不正确,所以主机名是 127.0.0.1:3000 为了解决这个问题,我在 conf 中添加了以下配置
location / { proxy_pass http://127.0.0.1:3021; proxy_http_version 1.1; //this was missing proxy_set_header Upgrade $http_upgrade; //this was missing proxy_set_header Connection 'upgrade'; //this was missing proxy_set_header Host $host; //this was missing proxy_cache_bypass $http_upgrade; //this was missing }
继续前进,您的 app.js 的流程很重要
应用程序
var app = express();
app.enable('trust proxy');
// app.use(cors()); //APP does not need cors because its GENERATING the long lasting session that needs to be read everywhere
//Everything else goes below this
app.use(cookieParser());
app.use(
session({
resave: false,
saveUninitialized: false,
secret: process.env.SESSION_SECRET,
cookie: {
domain: '.domain.com',
maxAge: 1209600000 // two weeks in milliseconds
},
store: new MongoStore({
mongooseConnection: mongoose.connection,
autoReconnect: true
})
})
);
var mainRouter = require('./routes/main');
网络
var app = express();
app.enable('trust proxy');
app.use(cors()); // TO read the cookie being set from elsewhere
var mainRouter = require('./routes/main');
最后
我必须清除我的 cookie 以删除任何误报 ^ 这是最烦人的一步
【问题讨论】:
标签: node.js express session passport.js express-session