目錄
? Session 原理簡要說明
🧩 示例項目 - 使用 Node.js + Express 實現簡單 Session 登錄
📁 文件結構
🔹 server.js (JavaScript)
🔸 index.html (HTML)
?? 程序運行步驟
? 程序運行效果
🎯 總結
在 Web 應用中,我們經常需要“記住”用戶,比如登錄狀態。這種“記住”就是會話管理(Session)。
? Session 原理簡要說明
-
Session 是服務器端的機制,用來保存用戶的數據(比如用戶名、權限等)。
-
每個 Session 會綁定一個唯一的 Session ID。
-
服務器會把這個 Session ID 發送給客戶端(瀏覽器),一般通過 Cookie 存儲。
-
瀏覽器下次請求時會自動帶上這個 Session ID,服務器就能識別出這個用戶了。
🧩 示例項目 - 使用 Node.js + Express 實現簡單 Session 登錄
我們來寫一個簡單的登錄系統,登錄成功后記住用戶信息,通過 Session 實現。
📁 文件結構
session-demo/
│
├── server.js ← Node.js 主程序 (JavaScript)
└── index.html ← 客戶端頁面 (HTML)
🔹 server.js (JavaScript)
// server.js
const express = require('express');
const session = require('express-session');
const path = require('path');const app = express();// 設置 session 中間件
app.use(session({secret: 'keyboard cat', // 用于加密 Session ID 的字符串resave: false,saveUninitialized: true,cookie: { maxAge: 60000 } // Session 有效時間:1分鐘
}));app.use(express.urlencoded({ extended: true }));
app.use(express.static(__dirname));// 登錄接口
app.post('/login', (req, res) => {const { username, password } = req.body;if (username === 'admin' && password === '123456') {req.session.user = username;res.send('登錄成功!歡迎你,' + username);} else {res.send('用戶名或密碼錯誤');}
});// 訪問首頁時檢查是否已登錄
app.get('/welcome', (req, res) => {if (req.session.user) {res.send('你已登錄,歡迎回來,' + req.session.user);} else {res.send('你還沒有登錄,請先登錄');}
});// 退出登錄
app.get('/logout', (req, res) => {req.session.destroy();res.send('你已退出登錄');
});// 啟動服務器
app.listen(3000, () => {console.log('服務器已啟動:http://localhost:3000');
});
🔸 index.html (HTML)
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh">
<head><meta charset="UTF-8"><title>Session 登錄示例</title>
</head>
<body><h2>登錄頁面</h2><form method="POST" action="/login">用戶名:<input type="text" name="username" /><br>密碼:<input type="password" name="password" /><br><button type="submit">登錄</button></form><br><a href="/welcome">查看登錄狀態</a><br><a href="/logout">退出登錄</a>
</body>
</html>
?? 程序運行步驟
-
安裝依賴:
npm install express express-session
-
啟動服務器:
node server.js
-
打開瀏覽器訪問:
http://localhost:3000
? 程序運行效果
-
打開頁面,輸入
admin
/123456
登錄。 -
登錄后服務器會設置 Session。
-
點擊「查看登錄狀態」會顯示歡迎信息。
-
點擊「退出登錄」后,Session 會被銷毀,再次訪問就會提示未登錄。
🎯 總結
這個例子通過 express-session
管理 Session,幫助你理解:
-
如何保存登錄狀態
-
Session 是服務器存儲用戶信息,客戶端只保存一個標識(Session ID)
?