欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Node.js實(shí)現(xiàn)一個(gè)HTTP服務(wù)器的方法示例

 更新時(shí)間:2019年05月13日 09:18:16   作者:凡沸  
這篇文章主要介紹了Node.js實(shí)現(xiàn)一個(gè)HTTP服務(wù)器的方法示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

項(xiàng)目地址

http server

題目

設(shè)計(jì)一個(gè)模擬HTTP服務(wù)端程序

自己設(shè)計(jì)一個(gè)WEB的程序,監(jiān)聽80端口。支持多客戶端連接,能滿足客戶的HTTP請(qǐng)求(瀏覽器訪問),包括以下功能:

1.基本功能:get、post(帶數(shù)據(jù)請(qǐng)求)、head請(qǐng)求

2.模擬登陸訪問,頁面redirector功能(設(shè)計(jì)登陸頁面login.html、主頁index.html,如果直接訪問index.html則跳轉(zhuǎn)到登陸頁面,只有登陸后才能打開主頁)

3.其他(如cookie)

效果展示

思路

用戶打開網(wǎng)址 127.0.0.1:8080 時(shí),客戶端發(fā)起 get 請(qǐng)求,請(qǐng)求路徑為 / ,服務(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ì)判斷請(qǐng)求頭是否攜帶 cookie ,若沒有則將請(qǐng)求重定向到 / 。

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 請(qǐng)求

let input = {
 name: document.querySelector('.input').value
}
let request = new XMLHttpRequest(); // 新建XMLHttpRequest對(duì)象
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對(duì)象
request.open('POST', '/login', true)
request.send(JSON.stringify(input))

如果客戶端發(fā)情 HEAD 請(qǐng)求,只返回相應(yīng)頭

if (request.url === '/getHead') {
 response.writeHead(200);
 response.end()
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論