Nodejs資料之web伺服器

2021-10-01 18:15:05 字數 1752 閱讀 8763

◆ 建立web伺服器示例:

// 引用系統模組

// 建立web伺服器

// 當客戶端傳送請求的時候

// 響應

res.end('');

});// 監聽3000埠

◆ 請求資訊獲取方法:

req.headers // 獲取請求報文

req.url // 獲取請求位址

req.method // 獲取請求方法

});

◆ get請求處理:

引數被放置在瀏覽器位址列中,獲取引數需要使用系統模組url來處理url位址

// 引入建立**伺服器的模組

// 用於處理url位址

const url = require('url');

// 當客戶端有請求來的時候

// 獲取請求方式

// req.method

// console.log(req.method);

// 獲取請求位址

// req.url

// console.log(req.url);

// 獲取請求報文資訊

// req.headers

// console.log(req.headers['accept']);

res.writehead(200, );

console.log(req.url);

// 1) 要解析的url位址

// 2) 將查詢引數解析成物件形式

let = url.parse(req.url, true);

console.log(query.name)

console.log(query.age)

if (pathname == '/index' || pathname == '/') else if (pathname == '/list') else

if (req.method == 'post') else if (req.method == 'get')

// res.end('');

});// 啟動監聽埠

console.log('**伺服器啟動成功');

◆ post請求處理:

引數被放置在請求體中進行傳輸,獲取post引數需要使用data事件和end事件。使用querystring系統模組將引數轉換為物件格式

// 用於建立**伺服器的模組

// 處理請求引數模組

const querystring = require('querystring');

// 當客戶端有請求來的時候

// post引數是通過事件的方式接受的

// data 當請求引數傳遞的時候觸發data事件

// end 當引數傳遞完成的時候觸發end事件

let postparams = '';

// 監聽引數傳輸事件

req.on('data', params => );

// 監聽引數傳輸完畢事件

req.on('end', () => );

res.end('ok');

});// 啟動監聽埠

console.log('**伺服器啟動成功');

Nodejs搭建web伺服器

node搭建本地服務 根據demo資料夾位置,右鍵啟動命令視窗 shift 右鍵 在此處開啟命令視窗 需是server.js資料夾路徑,在命令列node server啟動服務 檢測node版本及npm版本 命令列輸入 node v 命令列輸入 npm v 建立伺服器,以及對應css和js檔案的引入和...

IIs之web伺服器,FTP伺服器

既往不戀,當下不雜,未來不迎。1 web伺服器也成為網頁伺服器或者http伺服器。2 web伺服器使用的協議是http或者https。3 http協議埠號 tcp 80,https協議埠號 tcp 443。ftp協議埠號 21。linux apache lamp tomcat nginx etc,第...

nodeJs建立最基本的web伺服器

引入http核心模組 引入fs模組 const fs require fs 引入path模組 const path require path 建立伺服器 為伺服器繫結請求事件 每請求一次,此段 執行一次,但必須開啟伺服器 server.on request req,res 開啟伺服器,此處3000表...