如何搭建Node.js服務(wù)器
1.基礎(chǔ)HTTP服務(wù)器:
- 添加了路由處理
- 添加了404錯誤處理
- 添加了服務(wù)器錯誤監(jiān)聽
2.靜態(tài)資源服務(wù)器:
- 使用異步文件操作
- 支持目錄自動索引(默認(rèn)加載 index.html)
- 自動檢測文件類型并設(shè)置正確Content-Type
- 更完善的錯誤處理
3.處理GET請求參數(shù)
- 提供了一個HTML表單用于測試
- 使用url模塊解析URL和查詢參數(shù)
- 清晰展示接收到的GET參數(shù)
4.處理POST請求參數(shù):
- 提供了一個HTML表單用于測試
- 使用流的方式處理POST數(shù)據(jù)
- 正確解析表單數(shù)據(jù)
- 清晰展示接收到的POST參數(shù)
一、HTTP模塊
const http = require("http"); // 創(chuàng)建服務(wù)器實例 const app = http.createServer((req, res) => { // 設(shè)置響應(yīng)頭,指定內(nèi)容類型和編碼 res.setHeader("Content-Type", "text/html;charset=utf-8"); // 根據(jù)請求路徑返回不同內(nèi)容 switch (req.url) { case "/": res.end("歡迎訪問主頁!"); break; case "/about": res.end("這是關(guān)于頁面!"); break; default: res.statusCode = 404; res.end("404 - 頁面未找到"); } }); // 監(jiān)聽端口并啟動服務(wù)器 app.listen(5000, () => { console.log("服務(wù)器已啟動!監(jiān)聽在 http://localhost:5000"); }); // 添加錯誤處理 app.on("error", (error) => { console.error(`服務(wù)器啟動失敗: ${error.message}`); });
二、靜態(tài)資源服務(wù)器
const http = require("http"); const fs = require("fs").promises; const path = require("path"); // 定義靜態(tài)資源目錄 const STATIC_DIR = path.join(__dirname, "static"); // 內(nèi)容類型映射表 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 { // 構(gòu)建文件路徑 let filePath = path.join(STATIC_DIR, req.url === "/" ? "index.html" : req.url); // 檢查文件是否存在 await fs.access(filePath); // 獲取文件狀態(tài) const stat = await fs.stat(filePath); if (stat.isDirectory()) { // 如果是目錄,嘗試默認(rèn)文件 filePath = path.join(filePath, "index.html"); await fs.access(filePath); } // 獲取文件擴(kuò)展名并確定內(nèi)容類型 const extname = path.extname(filePath); const contentType = CONTENT_TYPES[extname] || "application/octet-stream"; // 設(shè)置響應(yīng)頭并發(fā)送文件內(nèi)容 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("服務(wù)器監(jiān)聽在 http://localhost:3000"); });
三、服務(wù)器獲取get請求參數(shù)
在./static下面寫一個index.html頁面,頁面中發(fā)送一個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和查詢參數(shù) 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請求參數(shù) res.end(`收到GET請求,參數(shù):${JSON.stringify(query)}`); } else { res.statusCode = 404; res.end("404 - 頁面未找到"); } }); app.listen(8888, () => { console.log("服務(wù)器已啟動!地址為: http://localhost:8888"); });
四、服務(wù)器獲取post請求參數(shù)
獲取post請求的參數(shù),通過給req綁定事件和end事件,來獲取監(jiān)聽的參數(shù),data事件一個接收的事件,end事件 當(dāng)post請求的參數(shù)都接收完畢,就出發(fā)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 = ""; // 監(jiān)聽data事件,收集數(shù)據(jù)塊 req.on("data", (chunk) => { body += chunk.toString(); }); // 監(jiān)聽end事件,數(shù)據(jù)接收完成 req.on("end", () => { // 解析表單數(shù)據(jù) const formData = qs.parse(body); // 返回處理結(jié)果 res.end(`收到POST請求,參數(shù):${JSON.stringify(formData)}`); }); } else { res.statusCode = 404; res.end("404 - 頁面未找到"); } }); app.listen(8888, () => { console.log("服務(wù)器已啟動!地址為: http://localhost:8888"); });
每個步驟的代碼都可以獨立運行,并且包含了必要的注釋以便理解
到此這篇關(guān)于搭建Node.js服務(wù)器的文章就介紹到這了,更多相關(guān)node.js服務(wù)器搭建內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Windows系統(tǒng)下使用Sublime搭建nodejs環(huán)境
最近在研究Nodejs開發(fā),俗話說,工欲善其事,必先利其器,當(dāng)然要找到一款用著順手的編輯器作為開始。這里我們選擇的是Sublime Text 3,除了漂亮的用戶界面,最吸引我的就是它的插件擴(kuò)展功能以及跨平臺特性。2015-04-04學(xué)習(xí) NodeJS 第八天:Socket 通訊實例
本篇文章主要介紹了學(xué)習(xí) NodeJS 第八天:Socket 通訊實例,非常具有實用價值,需要的朋友可以參考下。2016-12-12Nest.js Controller路由和請求處理強(qiáng)大功能解析
這篇文章主要為大家,介紹了Nest.js Controller路由和請求處理強(qiáng)大功能解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12Bun入門學(xué)習(xí)教程吊打Node或Deno的現(xiàn)代JS運行時
這篇文章主要為大家介紹了一款吊打Node或Deno的現(xiàn)代JS運行時,Bun入門學(xué)習(xí)教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07