Node.js實現一個HTTP伺服器
專案地址
題目
設計一個模擬HTTP服務端程式
自己設計一個WEB的程式,監聽80埠。支援多客戶端連線,能滿足客戶的HTTP請求(瀏覽器訪問),包括以下功能:
1.基本功能:get、post(帶資料請求)、head請求
2.模擬登陸訪問,頁面redirector功能(設計登陸頁面login.html、主頁index.html,如果直接訪問index.html則跳轉到登陸頁面,只有登陸後才能開啟主頁)
3.其他(如cookie)
效果展示
思路
- 使用者開啟網址
127.0.0.1:8080
時,客戶端發起 get 請求,請求路徑為/
,服務端返回 login.html 頁面。
if (request.url === '/') { fs.readFile('./login.html', function (err, data) { if (!err) { response.writeHead(200, { "Content-Type": "text/html;charset=UTF-8" }); response.end(data) } else { throw err; } }); }
- 當用戶試圖通過瀏覽器地址訪問
/index
時,服務端會判斷請求頭是否攜帶 cookie ,若沒有則將請求重定向到/
。
if (!request.headers.cookie) { response.writeHead(301, { 'Location': '/' }) response.end() }
- 如果有攜帶 cookie ,則將瀏覽器重定向到 index.html 頁面
window.location.href = '/index'
- 使用者在 login.html 介面輸入使用者名稱並點選登入,客戶端會攜帶使用者名稱發起一個 post 請求
let input = { name: document.querySelector('.input').value } let request = new XMLHttpRequest(); // 新建XMLHttpRequest物件 request.open('POST', '/login', true) request.send(JSON.stringify(input))
- 服務端接收引數,設定 cookie
response.writeHead(200, { // cookie只能設定當前域名和父域名,同級域名無效 'Set-Cookie': `name=${json.name}`, 'Content-Type': 'text/plain', }) response.end()
- 如果客戶端發情 HEAD 請求,只返回相應頭
if (request.url === '/getHead') { response.writeHead(200); response.end() }