Node.js 之 http 模組
阿新 • • 發佈:2021-12-23
Node.js 提供了 http 模組,http 模組主要用於搭建 HTTP 服務端和客戶端,使用 HTTP 伺服器或客戶端功能必須呼叫 http 模組,程式碼如下:
import http from 'http'
以下是演示一個最基本的 HTTP 伺服器架構(使用 8080 埠),
服務端
建立 server.js 檔案,程式碼如下所示:
import http from 'http' import fs from 'fs' import url from 'url' // 建立伺服器 http.createServer(function (request, response) {// 解析請求,包括檔名 var pathname = url.parse(request.url).pathname; // 輸出請求的檔名 console.log("Request for " + pathname + " received."); // 從檔案系統中讀取請求的檔案內容 fs.readFile(pathname.substr(1), function (err, data) { if (err) { console.log(err); // HTTP 狀態碼: 404 : NOT FOUND// Content Type: text/html response.writeHead(404, { 'Content-Type': 'text/html' }); } else { // HTTP 狀態碼: 200 : OK // Content Type: text/html response.writeHead(200, { 'Content-Type': 'text/html' }); // 響應檔案內容 response.write(data.toString()); }// 傳送響應資料 response.end(); }); }).listen(8080); // 控制檯會輸出以下資訊 console.log('Server running at http://127.0.0.1:8080/');
接下來在該目錄下建立一個 index.html 檔案,程式碼如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>node-server</title> </head> <body> <h1>我的第一個標題</h1> <p>我的第一個段落。</p> </body> </html>
執行 server.js 檔案:
$ node server.js
Server running at http://127.0.0.1:8080/
接著我們在瀏覽器中開啟地址:http://127.0.0.1:8080/index.html,顯示如下圖所示:
執行 server.js 的控制檯輸出資訊如下:
Server running at http://127.0.0.1:8080/
Request for /index.html received. # 客戶端請求資訊
客戶端
Node 建立 Web 客戶端需要引入 http 模組,建立 client.js 檔案,程式碼如下所示:
var http = require('http'); // 用於請求的選項 var options = { host: 'localhost', port: '8080', path: '/index.html' }; // 處理響應的回撥函式 var callback = function(response){ // 不斷更新資料 var body = ''; response.on('data', function(data) { body += data; }); response.on('end', function() { // 資料接收完成 console.log(body); }); } // 向服務端傳送請求 var req = http.request(options, callback); req.end();
新開一個終端,執行 client.js 檔案,輸出結果如下:
$ node client.js
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>node-server</title>
</head>
<body>
<h1>我的第一個標題</h1>
<p>我的第一個段落。</p>
</body>
</html>
執行 server.js 的控制檯輸出資訊如下:
Server running at http://127.0.0.1:8080/
Request for /index.html received. # 客戶端請求資訊