Node.js實(shí)現(xiàn)一個(gè)HTTP服務(wù)器的方法示例
項(xiàng)目地址
題目
設(shè)計(jì)一個(gè)模擬HTTP服務(wù)端程序
自己設(shè)計(jì)一個(gè)WEB的程序,監(jiān)聽80端口。支持多客戶端連接,能滿足客戶的HTTP請求(瀏覽器訪問),包括以下功能:
1.基本功能:get、post(帶數(shù)據(jù)請求)、head請求
2.模擬登陸訪問,頁面redirector功能(設(shè)計(jì)登陸頁面login.html、主頁index.html,如果直接訪問index.html則跳轉(zhuǎn)到登陸頁面,只有登陸后才能打開主頁)
3.其他(如cookie)
效果展示

思路
用戶打開網(wǎng)址 127.0.0.1:8080 時(shí),客戶端發(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;
}
});
}
當(dāng)用戶試圖通過瀏覽器地址訪問 /index 時(shí),服務(wù)端會(huì)判斷請求頭是否攜帶 cookie ,若沒有則將請求重定向到 / 。
if (!request.headers.cookie) {
response.writeHead(301, { 'Location': '/' })
response.end()
}
如果有攜帶 cookie ,則將瀏覽器重定向到 index.html 頁面
window.location.href = '/index'
用戶在 login.html 界面輸入用戶名并點(diǎn)擊登錄,客戶端會(huì)攜帶用戶名發(fā)起一個(gè) 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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Node.js查找當(dāng)前目錄下文件夾實(shí)例代碼
本篇文章主要介紹了Node.js查找當(dāng)前目錄下文件夾實(shí)例代碼,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-03-03
Node.js實(shí)現(xiàn)mysql連接池使用事務(wù)自動(dòng)回收連接的方法示例
這篇文章主要介紹了Node.js實(shí)現(xiàn)mysql連接池使用事務(wù)自動(dòng)回收連接的方法,結(jié)合實(shí)例形式分析了node.js操作mysql連接池實(shí)現(xiàn)基于事務(wù)的連接回收操作相關(guān)技巧,需要的朋友可以參考下2018-02-02
node.js利用redis數(shù)據(jù)庫緩存數(shù)據(jù)的方法
Redis數(shù)據(jù)庫采用極簡的設(shè)計(jì)思想,最新版的源碼包還不到2Mb。其在使用上也有別于一般的數(shù)據(jù)庫。下面這篇文章就來給大家介紹了node.js利用redis數(shù)據(jù)庫緩存數(shù)據(jù)的方法,需要的朋友可以參考借鑒,下面來一起看看吧。2017-03-03

