diff --git a/backend/server.js b/backend/server.js index 8826da2..446014a 100644 --- a/backend/server.js +++ b/backend/server.js @@ -18,8 +18,36 @@ const { generateToken, authMiddleware, adminMiddleware } = require('./auth'); const app = express(); const PORT = process.env.PORT || 40001; + +// 配置CORS +const allowedOrigins = process.env.ALLOWED_ORIGINS + ? process.env.ALLOWED_ORIGINS.split(',').map(origin => origin.trim()) + : ['*']; + +const corsOptions = { + credentials: true, + origin: (origin, callback) => { + // 允许所有来源(仅限开发环境) + if (allowedOrigins.includes('*')) { + if (process.env.NODE_ENV === 'production') { + console.warn('⚠️ 警告: 生产环境建议配置具体的ALLOWED_ORIGINS,而不是使用 *'); + } + callback(null, true); + return; + } + + // 允许来自配置列表中的域名 + if (!origin || allowedOrigins.includes(origin)) { + callback(null, true); + } else { + console.warn(`[CORS] 拒绝来自未授权来源的请求: ${origin}`); + callback(new Error('CORS策略不允许来自该来源的访问')); + } + } +}; + // 中间件 -app.use(cors({ credentials: true, origin: true })); +app.use(cors(corsOptions)); app.use(express.json()); app.use(cookieParser());