1.基礎HTTP服務器:
- 添加了路由處理
- 添加了404錯誤處理
- 添加了服務器錯誤監聽
2.靜態資源服務器:
- 使用異步文件操作
- 支持目錄自動索引(默認加載 index.html)
- 自動檢測文件類型并設置正確Content-Type
- 更完善的錯誤處理
3.處理GET請求參數
- 提供了一個HTML表單用于測試
- 使用url模塊解析URL和查詢參數
- 清晰展示接收到的GET參數
4.處理POST請求參數:
- 提供了一個HTML表單用于測試
- 使用流的方式處理POST數據
- 正確解析表單數據
- 清晰展示接收到的POST參數
一、HTTP模塊
const http = require("http");// 創建服務器實例
const app = http.createServer((req, res) => {// 設置響應頭,指定內容類型和編碼res.setHeader("Content-Type", "text/html;charset=utf-8");// 根據請求路徑返回不同內容switch (req.url) {case "/":res.end("歡迎訪問主頁!");break;case "/about":res.end("這是關于頁面!");break;default:res.statusCode = 404;res.end("404 - 頁面未找到");}
});// 監聽端口并啟動服務器
app.listen(5000, () => {console.log("服務器已啟動!監聽在 http://localhost:5000");
});// 添加錯誤處理
app.on("error", (error) => {console.error(`服務器啟動失敗: ${error.message}`);
});
二、靜態資源服務器
const http = require("http");
const fs = require("fs").promises;
const path = require("path");// 定義靜態資源目錄
const STATIC_DIR = path.join(__dirname, "static");// 內容類型映射表
const CONTENT_TYPES = {".html": "text/html",".css": "text/css",".js": "text/javascript",".json": "application/json",".png": "image/png",".jpg": "image/jpeg",".gif": "image/gif",".svg": "image/svg+xml",".txt": "text/plain"
};const app = http.createServer(async (req, res) => {try {// 構建文件路徑let filePath = path.join(STATIC_DIR, req.url === "/" ? "index.html" : req.url);// 檢查文件是否存在await fs.access(filePath);// 獲取文件狀態const stat = await fs.stat(filePath);if (stat.isDirectory()) {// 如果是目錄,嘗試默認文件filePath = path.join(filePath, "index.html");await fs.access(filePath);}// 獲取文件擴展名并確定內容類型const extname = path.extname(filePath);const contentType = CONTENT_TYPES[extname] || "application/octet-stream";// 設置響應頭并發送文件內容res.setHeader("Content-Type", contentType);const fileContent = await fs.readFile(filePath);res.end(fileContent);} catch (error) {// 處理錯誤res.statusCode = 404;res.end("404 - 文件未找到");}
});app.listen(3000, () => {console.log("服務器監聽在 http://localhost:3000");
});
三、服務器獲取get請求參數
在./static下面寫一個index.html頁面,頁面中發送一個get請求
const http = require("http");
const url = require("url");
const qs = require("querystring");const app = http.createServer((req, res) => {res.setHeader("Content-Type", "text/html;charset=utf-8");// 解析URL和查詢參數const parsedUrl = url.parse(req.url, true);const pathname = parsedUrl.pathname;const query = parsedUrl.query;if (pathname === "/") {// 返回表單頁面const formHtml = `<form method="GET" action="/api"><input type="text" name="username" placeholder="用戶名"><input type="password" name="password" placeholder="密碼"><button type="submit">提交</button></form>`;res.end(formHtml);} else if (pathname === "/api") {// 處理GET請求參數res.end(`收到GET請求,參數:${JSON.stringify(query)}`);} else {res.statusCode = 404;res.end("404 - 頁面未找到");}
});app.listen(8888, () => {console.log("服務器已啟動!地址為: http://localhost:8888");
});
?四、服務器獲取post請求參數
獲取post請求的參數,通過給req綁定事件和end事件,來獲取監聽的參數,data事件一個接收的事件,end事件 當post請求的參數都接收完畢,就出發end事件
const http = require("http");
const qs = require("querystring");const app = http.createServer((req, res) => {res.setHeader("Content-Type", "text/html;charset=utf-8");if (req.url === "/") {// 返回表單頁面const formHtml = `<form method="POST" action="/api"><input type="text" name="username" placeholder="用戶名"><input type="password" name="password" placeholder="密碼"><button type="submit">提交</button></form>`;res.end(formHtml);} else if (req.url === "/api" && req.method === "POST") {// 處理POST請求let body = "";// 監聽data事件,收集數據塊req.on("data", (chunk) => {body += chunk.toString();});// 監聽end事件,數據接收完成req.on("end", () => {// 解析表單數據const formData = qs.parse(body);// 返回處理結果res.end(`收到POST請求,參數:${JSON.stringify(formData)}`);});} else {res.statusCode = 404;res.end("404 - 頁面未找到");}
});app.listen(8888, () => {console.log("服務器已啟動!地址為: http://localhost:8888");
});
每個步驟的代碼都可以獨立運行,并且包含了必要的注釋以便理解