فهرست منبع

'登录功能优化'

admincjy 4 هفته پیش
والد
کامیت
d6aa8efa26
1فایلهای تغییر یافته به همراه58 افزوده شده و 5 حذف شده
  1. 58 5
      server.js

+ 58 - 5
server.js

@@ -36,7 +36,11 @@ function validatePath(fullPath, baseDir) {
 }
 
 // 中间件
-app.use(cors());
+// CORS 配置 - 允许前端携带凭证(cookies)
+app.use(cors({
+  origin: true, // 允许所有来源(生产环境建议指定具体域名)
+  credentials: true // 允许携带凭证
+}));
 app.use(express.json({ limit: '10mb' })); // 增加请求体大小限制到10MB
 app.use(express.urlencoded({ limit: '10mb', extended: true }));
 
@@ -48,8 +52,12 @@ app.use(session({
   cookie: {
     maxAge: 7 * 24 * 60 * 60 * 1000, // 7天
     httpOnly: true,
-    secure: false // 如果使用 HTTPS,设置为 true
-  }
+    secure: false, // 如果使用 HTTPS,设置为 true
+    sameSite: 'lax', // 允许跨站点请求携带 cookie
+    path: '/' // Cookie 路径
+  },
+  name: 'cjydocs.sid', // Session cookie 名称
+  rolling: true // 每次请求时重置过期时间
 }));
 
 // 登录验证中间件
@@ -69,9 +77,20 @@ function requireAuth(req, res, next) {
 
 // 根路径重定向处理
 app.get('/', (req, res) => {
+  console.log('访问首页 - Session状态:', req.session ? req.session.isAuthenticated : 'no session');
+
   if (req.session && req.session.isAuthenticated) {
-    res.sendFile(path.join(__dirname, 'public', 'index.html'));
+    const indexPath = path.join(__dirname, 'public', 'index.html');
+    console.log('发送首页文件:', indexPath);
+
+    res.sendFile(indexPath, (err) => {
+      if (err) {
+        console.error('发送首页文件失败:', err);
+        res.status(500).json({ error: '无法加载首页', details: err.message });
+      }
+    });
   } else {
+    console.log('未登录,重定向到登录页');
     res.redirect('/login.html');
   }
 });
@@ -102,15 +121,28 @@ app.get('/login.html', (req, res) => {
 // API: 登录
 app.post('/api/login', (req, res) => {
   const { password } = req.body;
+  console.log('登录尝试 - IP:', req.ip, 'Session ID:', req.sessionID);
 
   if (!password || typeof password !== 'string') {
+    console.log('登录失败: 密码格式错误');
     return res.status(400).json({ error: '请输入密码' });
   }
 
   if (password === PASSWORD) {
     req.session.isAuthenticated = true;
-    res.json({ success: true, message: '登录成功' });
+    console.log('登录成功 - Session ID:', req.sessionID, 'Session数据:', req.session);
+
+    // 保存 session 后再响应
+    req.session.save((err) => {
+      if (err) {
+        console.error('Session保存失败:', err);
+        return res.status(500).json({ error: '登录失败,请重试' });
+      }
+      console.log('Session保存成功');
+      res.json({ success: true, message: '登录成功' });
+    });
   } else {
+    console.log('登录失败: 密码错误');
     res.status(401).json({ error: '密码错误' });
   }
 });
@@ -439,7 +471,28 @@ function parseIndexMd(content) {
   return structure;
 }
 
+// 全局错误处理中间件
+app.use((err, req, res, next) => {
+  console.error('全局错误捕获:', err);
+  res.status(err.status || 500).json({
+    error: '服务器内部错误',
+    message: err.message,
+    path: req.path
+  });
+});
+
+// 404 处理
+app.use((req, res) => {
+  console.log('404 未找到:', req.method, req.path);
+  res.status(404).json({
+    error: '页面不存在',
+    path: req.path
+  });
+});
+
 // 启动服务器
 app.listen(PORT, () => {
   console.log(`服务器运行在 http://localhost:${PORT}`);
+  console.log(`密码: ${PASSWORD}`);
+  console.log(`Session 有效期: 7天`);
 });