我的 Express 应用程序中的 connect.sid cookie 遇到问题。一切都在我的本地环境中完美运行,cookie 已按预期创建并持续存在。但是,一旦我部署到生产环境并启用 CORS,connect.sid cookie 似乎在生成后很快就消失了。
环境详情: 框架:Express.js 会话中间件:express-session
onst corsOptions = {
origin: ['https://voiceblogify.netlify.app'],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
credentials: true,
allowedHeaders: ['Content-Type', 'Authorization'],
};
app.use(cors(corsOptions));
app.use(session({
secret: process.env.SECRET_SESSION_KEY,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24, // 1 day
secure: process.env.NODE_ENV === 'production',
httpOnly: true,
sameSite: 'None', domain: '.voiceblogify.netlify.app'
},
}));
[enter image description here](https://i.sstatic.net/6JgEmdBM.png)
live link https://voiceblogify.netlify.app/
问题描述: 本地环境:connect.sid cookie 已创建并持续存在,没有任何问题。 生产环境:启用 CORS 并将 secure 标志设置为 true 后,会生成 connect.sid cookie,但不久后就会消失。 附加观察: 服务器位于代理后面,因此我设置了 app.set('trust proxy', 1);。 我添加了日志记录来监视每个请求的 cookie 和会话状态。 问题:
https://voiceblogify.netlify.app/
useEffect(() => {
async function checkAuth() {
try {
const response = await fetch('https://voiceblogify-backend.onrender.com/status', {
method: 'GET',
credentials: 'include'
});
const data = await response.json();
console.log(data)
if (data.authenticated) {
setIsAuthenticated(true);
setUser({
name: data.name,
profilepicurl: data.profilepic,
userId: data.id
});
setPaidMember(false);
}
} catch (error) {
console.error('Error checking auth:', error);
}
}
checkAuth();
}, []);
从正面呼叫
为什么 connect.sid cookie 在生产中很快就被销毁了? 是否有我可能缺少的与 CORS 或会话管理相关的特定配置? 代理配置方式是否存在任何可能影响 cookie 传输的问题?
可能原因:
配置示例:
CORS 配置:
const express = require('express');
const cors = require('cors'); // Import the cors package
const app = express();
const corsOptions = {
origin: 'https://voiceblogify.netlify.app', // Your frontend origin
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
credentials: true, // Allow cookies
allowedHeaders: ['Content-Type', 'Authorization'],
};
app.use(cors(corsOptions)); // Use the cors middleware
会话配置:
app.use(session({
secret: process.env.SECRET_SESSION_KEY,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24, // 1 day
secure: true, // Set to true in production (HTTPS)
httpOnly: true,
sameSite: 'None', // For cross-site requests
domain: '.voiceblogify.netlify.app', // Your frontend domain
},
}));
前端获取请求:
useEffect(() => {
async function checkAuth() {
try {
const response = await fetch('https://voiceblogify-backend.onrender.com/status', {
method: 'GET',
credentials: 'include', // Important: include credentials
});
const data = await response.json();
if (data.authenticated) {
// Handle authenticated user
}
} catch (error) {
console.error('Error checking auth:', error);
}
}
checkAuth();
}, []);