http 模塊是 Node.js 中的核心模塊之一,專門用于構建基于 HTTP 的網絡應用程序。它允許創建 HTTP 服務器和客戶端,處理網絡請求和響應。
1.?核心 API 詳解
1.1. http.createServer([options][, requestListener])
用于創建 HTTP 服務器的核心方法,返回一個 http.Server 實例,可監聽指定端口并處理請求。
options(可選):用于提供服務器配置,允許指定 HTTP/1.1、HTTP/2 等協議。
requestListener(可選):一個回調函數,在每次接收到客戶端請求時調用。
const http = require('http');
const server = http.createServer((req, res) => {res.statusCode = 200;res.setHeader('Content-Type', 'text/plain');res.end('Hello, world!\n');
});
server.listen(3000, '127.0.0.1', () => {console.log('Server running at http://127.0.0.1:3000/');
});
req:包含請求的詳細信息,比如 URL、HTTP 方法、請求頭等。
res:用于響應客戶端請求,可以設置狀態碼、響應頭以及響應體。
1.2.?request and response Objects
1. http.IncomingMessage
表示服務器接收到的請求,是一個可讀流,用于獲取請求體和元數據。
常用屬性:
req.method:請求的方法。
req.url:請求的路徑和查詢參數。
req.headers:請求的頭部信息。
2. http.ServerResponse
表示服務器對客戶端的響應,是一個可寫流,用于發送響應數據。
常用方法:
res.writeHead(statusCode[, headers]):設置狀態碼和頭部信息。
res.end([data[, encoding]][, callback]):結束響應并可以發送數據。
1.3. http.request(options[, callback])
用于創建 HTTP 客戶端請求。
const options = {hostname: 'www.google.com',port: 80,path: '/',method: 'GET',
};
const req = http.request(options, (res) => {let data = '';res.on('data', (chunk) => {data += chunk;});res.on('end', () => {console.log(data);});
});
req.on('error', (e) => {console.error(`Problem with request: ${e.message}`);
});
req.end();
options:用于配置請求的目標、方法、頭信息等。
callback:處理響應的回調函數。
1.4.?http.get(options[, callback])
這是一個簡化版的 http.request,專門用于 GET 請求,自動調用 req.end(),不需要顯式調用。
http.get('http://www.google.com', (res) => {res.on('data', (chunk) => {console.log(`Data chunk: ${chunk}`);});res.on('end', () => {console.log('No more data.');});
});
2.?實戰項目:簡單的 HTTP 服務器與客戶端
創建一個簡單的 HTTP 服務器,它可以響應客戶端的 GET 和 POST 請求。同時,通過客戶端請求獲取服務器上的數據。
2.1.?創建 HTTP 服務器
在服務器端,接受 GET 和 POST 請求,并返回不同的響應。
const http = require('http');
const server = http.createServer((req, res) => {if (req.method === 'GET' && req.url === '/') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ message: 'Welcome to the GET request!' }));} else if (req.method === 'POST' && req.url === '/submit') {let body = '';req.on('data', (chunk) => {body += chunk.toString();});req.on('end', () => {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ message: 'Data received!', data: body }));});} else {res.writeHead(404, { 'Content-Type': 'text/plain' });res.end('404 Not Found');}
});
server.listen(3000, () => {console.log('Server listening on port 3000');
});
2.2.?創建 HTTP 客戶端
客戶端將發送 GET 和 POST 請求來與服務器進行交互。
const http = require('http');
// Send GET request
http.get('http://localhost:3000', (res) => {let data = '';res.on('data', (chunk) => {data += chunk;});res.on('end', () => {console.log('GET Response:', data);});
});
// Send POST request
const postData = JSON.stringify({ name: 'John', age: 30 });
const options = {hostname: 'localhost',port: 3000,path: '/submit',method: 'POST',headers: {'Content-Type': 'application/json','Content-Length': postData.length,},
};
const req = http.request(options, (res) => {let data = '';res.on('data', (chunk) => {data += chunk;});res.on('end', () => {console.log('POST Response:', data);});
});
req.write(postData);
req.end();
通過 http 模塊直接實現 WebSocket (WS) 協議是一項深入底層協議的工作。WebSocket 是基于 TCP 的協議,在其通信過程中,依賴于 HTTP 協議的握手機制,但通信方式和 HTTP 不同,它允許建立一個長期的、雙向的連接。為了實現 WebSocket 服務器,需要結合對 HTTP 和 WebSocket 握手機制、數據幀協議以及 TCP/IP 模型的理解。