項目地址
題目
設計一個模擬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
let input = { name: document.querySelector('.input').value}let request = new XMLHttpRequest(); // 新建XMLHttpRequest對象request.open('POST', '/login', true)request.send(JSON.stringify(input))
如果客戶端發情 HEAD 請求,只返回相應頭
if (request.url === '/getHead') { response.writeHead(200); response.end()}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答