server.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const express = require('express');
  2. const path = require('path')
  3. const cors = require('cors');
  4. const bodyParser = require('body-parser');
  5. const session = require('express-session');
  6. const host = '0.0.0.0'; // 服务器的 IP 地址
  7. const port = 3000;
  8. const app = express();
  9. app.use(cors());
  10. // 模拟用户数据库
  11. const users = {
  12. "user1": "user1",
  13. "user2": "user2",
  14. }
  15. app.use(bodyParser.json());
  16. app.use(session({
  17. secret: 'yourSecretKey',
  18. resave: false,
  19. saveUninitialized: true,
  20. cookie: {
  21. maxAge: 30 * 60 * 1000, // 30 分钟
  22. }
  23. }));
  24. function isAuthenticated(req, res, next) {
  25. if (req.path.endsWith('.css') || req.path.endsWith('.js')) {
  26. return next();
  27. }
  28. if (req.path === '/login.html' || req.path === '/login') {
  29. return next();
  30. }
  31. if (req.session.username) {
  32. return next(); // 已登录
  33. } else {
  34. res.redirect('/login.html'); // 未登录
  35. }
  36. }
  37. app.use(isAuthenticated);
  38. app.use(express.static(path.join(__dirname, './html/')));
  39. app.get('*', (req, res) => {
  40. res.sendFile(path.join(__dirname, './html/gm3.html'));
  41. });
  42. // 登录接口
  43. app.post('/login', (req, res) => {
  44. const {username, password } = req.body;
  45. console.log(req.body)
  46. if (users[username] && users[username]==password) {
  47. req.session.username = username;
  48. res.status(200).json({ message: 'Login successful' });
  49. } else {
  50. res.status(401).json({ message: 'Invalid username' });
  51. }
  52. });
  53. // 检查登录状态接口
  54. app.get('/check-auth', (req, res) => {
  55. if (req.session.username) {
  56. res.status(200).json({ loggedIn: true });
  57. } else {
  58. res.status(401).json({ loggedIn: false });
  59. }
  60. });
  61. app.listen(port, host, () => {
  62. console.log(`Server is running at http://${host}:${port}`);
  63. });