如何在生产中设置快速会话。快速会话在 https 中不起作用
How to set up express-session in production. Express-session is not working in https
我使用 express-session 和 connect-mongo 来存储会话,它在开发环境中运行良好。但是,它不会在生产中保持会话。当我登录时,我可以通过 console.log(req.sesssion)
在服务器上获取会话。但是,如果我移动到另一个 url.
,则会话未定义
const whitelist = ['https://example.com', 'https://www.example.com'];
const corsOptions = {
origin(origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
};
app.use(cors(corsOptions));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
store,
}));
找了大概一天的时间。最后,我找到了所有令人头疼的问题。该问题与 http 请求有关。我使用 axios
作为请求,默认情况下,Axios 不获取发送或接收任何 cookie。为了能够使用 cookie,我需要为我发出的每个请求传递 Axios 配置选项。{withCredentials: true}
。感谢 .
Axios.post(url, data, { withCredentials: true })...
但是,这让我想到了另一个问题。
"The value of the 'Access-Control-Allow-Credentials' header in the
response is '' which must be 'true' when the request's credentials
mode is 'include'."
然后我将 credentials: true
添加到我的 cors() 模块 。
const corsOptions = {
origin(origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true
};
现在我的项目已经上线并为用户服务,让他们的生活更轻松:)。
我使用 express-session 和 connect-mongo 来存储会话,它在开发环境中运行良好。但是,它不会在生产中保持会话。当我登录时,我可以通过 console.log(req.sesssion)
在服务器上获取会话。但是,如果我移动到另一个 url.
const whitelist = ['https://example.com', 'https://www.example.com'];
const corsOptions = {
origin(origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
};
app.use(cors(corsOptions));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
store,
}));
找了大概一天的时间。最后,我找到了所有令人头疼的问题。该问题与 http 请求有关。我使用 axios
作为请求,默认情况下,Axios 不获取发送或接收任何 cookie。为了能够使用 cookie,我需要为我发出的每个请求传递 Axios 配置选项。{withCredentials: true}
。感谢
Axios.post(url, data, { withCredentials: true })...
但是,这让我想到了另一个问题。
"The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'."
然后我将 credentials: true
添加到我的 cors() 模块
const corsOptions = {
origin(origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true
};
现在我的项目已经上线并为用户服务,让他们的生活更轻松:)。