項目地址
題目
設(shè)計一個模擬HTTP服務(wù)端程序
自己設(shè)計一個WEB的程序,監(jiān)聽80端口。支持多客戶端連接,能滿足客戶的HTTP請求(瀏覽器訪問),包括以下功能:
1.基本功能:get、post(帶數(shù)據(jù)請求)、head請求
2.模擬登陸訪問,頁面redirector功能(設(shè)計登陸頁面login.html、主頁index.html,如果直接訪問index.html則跳轉(zhuǎn)到登陸頁面,只有登陸后才能打開主頁)
3.其他(如cookie)
效果展示
思路
用戶打開網(wǎng)址 127.0.0.1:8080
時,客戶端發(fā)起 get 請求,請求路徑為 /
,服務(wù)端返回 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
時,服務(wù)端會判斷請求頭是否攜帶 cookie ,若沒有則將請求重定向到 /
。
if (!request.headers.cookie) { response.writeHead(301, { 'Location': '/' }) response.end()}
如果有攜帶 cookie ,則將瀏覽器重定向到 index.html 頁面
window.location.href = '/index'
用戶在 login.html 界面輸入用戶名并點擊登錄,客戶端會攜帶用戶名發(fā)起一個 post 請求
let input = { name: document.querySelector('.input').value}let request = new XMLHttpRequest(); // 新建XMLHttpRequest對象request.open('POST', '/login', true)request.send(JSON.stringify(input))
服務(wù)端接收參數(shù),設(shè)置 cookie
let input = { name: document.querySelector('.input').value}let request = new XMLHttpRequest(); // 新建XMLHttpRequest對象request.open('POST', '/login', true)request.send(JSON.stringify(input))
如果客戶端發(fā)情 HEAD 請求,只返回相應(yīng)頭
if (request.url === '/getHead') { response.writeHead(200); response.end()}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答