1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- const express = require('express');
- const path = require('path')
- const cors = require('cors');
- const bodyParser = require('body-parser');
- const session = require('express-session');
- const host = '0.0.0.0'; // 服务器的 IP 地址
- const port = 3000;
- const app = express();
- app.use(cors());
- // 模拟用户数据库
- const users = {
- "user1": "user1",
- "user2": "user2",
- }
- app.use(bodyParser.json());
- app.use(session({
- secret: 'yourSecretKey',
- resave: false,
- saveUninitialized: true,
- cookie: {
- maxAge: 30 * 60 * 1000, // 30 分钟
- }
- }));
- function isAuthenticated(req, res, next) {
- if (req.path.endsWith('.css') || req.path.endsWith('.js')) {
- return next();
- }
- if (req.path === '/login.html' || req.path === '/login') {
- return next();
- }
- if (req.session.username) {
- return next(); // 已登录
- } else {
- res.redirect('/login.html'); // 未登录
- }
- }
- app.use(isAuthenticated);
- app.use(express.static(path.join(__dirname, './html/')));
- app.get('*', (req, res) => {
- res.sendFile(path.join(__dirname, './html/gm3.html'));
- });
- // 登录接口
- app.post('/login', (req, res) => {
- const {username, password } = req.body;
- console.log(req.body)
- if (users[username] && users[username]==password) {
- req.session.username = username;
- res.status(200).json({ message: 'Login successful' });
- } else {
- res.status(401).json({ message: 'Invalid username' });
- }
- });
- // 检查登录状态接口
- app.get('/check-auth', (req, res) => {
- if (req.session.username) {
- res.status(200).json({ loggedIn: true });
- } else {
- res.status(401).json({ loggedIn: false });
- }
- });
- app.listen(port, host, () => {
- console.log(`Server is running at http://${host}:${port}`);
- });
|