npm init 可用npm 來調試node項目
瀏覽器中的頂級對象時window
<ref *1> Object [global] { global: [Circular *1], clearImmediate: [Function: clearImmediate], setImmediate: [Function: setImmediate] { [Symbol(nodejs.util.promisify.custom)]: [Getter] }, clearInterval: [Function: clearInterval], clearTimeout: [Function: clearTimeout], setInterval: [Function: setInterval], setTimeout: [Function: setTimeout] { [Symbol(nodejs.util.promisify.custom)]: [Getter] }, queueMicrotask: [Function: queueMicrotask], structuredClone: [Function: structuredClone], atob: [Getter/Setter], btoa: [Getter/Setter], performance: [Getter/Setter], fetch: [Function: fetch], crypto: [Getter] }
node中的頂級對象時global
module.exports 與 require
const GetName = ()=>{ return "jack" ; }; const GetAge = ()=>{ return 18; }; module.exports = { GetName, GetAge }
const {GetName,GetAge} = require("./utils"); GetName(); GetAge();
默認情況下,Node.js 將 JavaScript 文件視為 CommonJS 模塊,需要使用:module.exports ={} 和 require 來導出導入。若使用export 與 import 報錯,需要將package.js中的:"type": "commonjs", 轉成 type": "module"
export default = methods 更適用于單個組件進行導出,可以隨意命名,并且一個js文件中只能有一個默認導出
export = {...methods} 更適用于多個方法的導出,不能隨意命名,但可以通過 import {methodName as methodSetName} 來進行命名,一個js文件中可有多個普通導出
值得注意的是,在一個js文件中,可以同時有多個普通導出與一個默認導出。
后端server配置CORS ,允許前端跨域發起請求
同源策略是一個安全機制,要求“協議+域名+端口”三者相同,否則瀏覽器會阻止網頁向不同源的服務器發送請求。
// Add CORS headers,允許跨域 res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5173'); //'http://localhost:5173/' 會報錯,不能加,因為這個CORS是根據字符串來匹配的 // 允許所有源 res.setHeader('Access-Control-Allow-Origin', '*'); // 也可以根據請求源動態設置,允許信任的請求源 const allowedOrigins = ['http://localhost:5173', 'https://yourapp.com', 'http://127.0.0.1:8080']; const origin = req.headers.origin; if (allowedOrigins.includes(origin)) { res.setHeader('Access-Control-Allow-Origin', origin); } res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
若前端在請求頭中自定義了某個屬性,你需要在后臺服務器中的CORS也定義上:
//前端 axios.get('http://localhost:8888/', { headers: { 'X-Custom-Header': 'foobar' } }) //后臺服務器 res.setHeader('Access-Control-Allow-Headers','Content-Type, Authorization, X-Custom-Header');
避免修改一次代碼就要重啟一次服務器
npm install nodemon
package-lock.js 是依賴項文件夾,類似于python中的requirement.txt,執行npm install 可下載所有的依賴項。并會將所有的依賴項存儲到文件夾node_modules里。同時,npm i 也能完成更新依賴包的作用。作用是為了防止將依賴包都放到github上
也可以在.gitignore中添加不推送到github中的文件夾/文件名
.gitignore | node_modules | ...all_requirement_packages
配置package.json文件,完成使用nodemon 來調試程序。
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "nodemon server.js", "dev": "nodemon server.js" },
.env文件
用于設置項目中的全局變量,不能有空格
PORT=8080
//實際使用 const PORT = process.env.PORT;
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "nodemon server.js", "dev": "nodemon --env-file=.env server.js" },
必須要加 --env-file=.env,否則指定的全局變量會顯示undefined
并且可以在.gitignore文件中,添加.env ,防止上傳到git
原生的node.js服務端
import http from 'http'; // const PORT = process.end.PORT; const PORT = process.env.PORT; const server = http.createServer((req, res) => { // Add CORS headers,解決跨域問題 res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5173'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Custom-Header'); //debug console.log(req.url); //客戶端請求的網址 console.log(req.method); //客戶端的請求方式 // For normal requests, proceed with your existing code res.writeHead(200, "OK", { 'Content-Type': 'text/html' }); res.write( `<h1>hello user</h1> <h2>Welcome to http my server</h2> <h3>Wish you have a good day</h3> ` ); res.end(JSON.stringify({ "message": "ok", "statusCode": 200, "data": { "name": "Jack", "age": 18, "home":"ShangHai", } })); }); server.listen(PORT, () => { console.log(`use ${PORT} port ,search: http://localhost:${PORT}/`); });
客戶端像后端發起get請求,為什么后臺打印:OPTIONS GET
這是由于:CORS預檢機制
當瀏覽器發起跨域請求時,會觸發CORS(跨源資源共享)機制。在特定情況下,瀏覽器會在實際請求前自動發送一個"預檢請求"(OPTIONS請求),這就是您在后臺看到OPTIONS和GET兩個請求的原因。
關于Access-Control-Max-Age的詳細說明
這個頭部信息的作用是告訴瀏覽器在指定的時間內(以秒為單位)可以緩存預檢請求的結果,而無需再次發送OPTIONS請求。這對于優化性能非常有益,特別是在頻繁發生跨域請求的應用中。
瀏覽器限制:不同瀏覽器對Access-Control-Max-Age的最大值有不同限制:
-
Chrome: 最大值為7200秒(2小時)
-
Firefox: 最大值為86400秒(24小時)
-
Safari: 沒有明確限制,但遵循標準建議
將獲取當前文件的路徑
import fs from 'fs/promises'; import url from 'url'; import path from 'path'; //get current path //import.meta.url 當前路徑的url export const GetCurrentPath = (importUrl) =>{ const fileName = url.fileURLToPath(importUrl); //將文件的url轉化為路徑 const dirName = path.dirname(fileName); //輸入:文件的路徑;輸出:文件所在目錄 return { fileName, dirName } } console.log(import.meta.url); //file:///C:/Users/32217/Desktop/%E9%A1%B9%E7%9B%AE/%E5%8C%BB%E7%96%97%E5%81%A5%E5%BA%B7%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F/code/front-end/server.js console.log(fileName); console.log(dirName); /* C:\Users\32217\Desktop\項目\醫療健康管理系統\code\front-end\server.js C:\Users\32217\Desktop\項目\醫療健康管理系統\code\front-end */
response.writeHead() 與 response.end() 必須配套使用,否則會響應超時!!!
Request
C:\Users\32217\Desktop\項目\醫療健康管理系統\code\front-end\public\404.html Using port 8888, visit: http://localhost:8888/ req.url:/Login req.method:POST <ref *2> IncomingMessage { _events: { close: undefined, error: undefined, data: undefined, end: undefined, readable: undefined }, _readableState: ReadableState { highWaterMark: 16384, buffer: [], bufferIndex: 0, length: 0, pipes: [], awaitDrainWriters: null, [Symbol(kState)]: 1315084 }, _maxListeners: undefined, socket: <ref *1> Socket { connecting: false, _hadError: false, _parent: null, _host: null, _closeAfterHandlingError: false, _events: { close: [Array], error: [Function: socketOnError], prefinish: undefined, finish: undefined, drain: [Function: bound socketOnDrain], data: [Function: bound socketOnData], end: [Array], readable: undefined, timeout: [Function: socketOnTimeout], resume: [Function: onSocketResume], pause: [Function: onSocketPause] }, _readableState: ReadableState { highWaterMark: 16384, buffer: [], bufferIndex: 0, length: 0, pipes: [], awaitDrainWriters: null, [Symbol(kState)]: 193997060 }, _writableState: WritableState { highWaterMark: 16384, length: 0, corked: 0, onwrite: [Function: bound onwrite], writelen: 0, bufferedIndex: 0, pendingcb: 0, [Symbol(kState)]: 17564420, [Symbol(kBufferedValue)]: null }, allowHalfOpen: true, _maxListeners: undefined, _eventsCount: 8, _sockname: null, _pendingData: null, _pendingEncoding: '', server: Server { maxHeaderSize: undefined, insecureHTTPParser: undefined, requestTimeout: 300000, headersTimeout: 60000, keepAliveTimeout: 5000, connectionsCheckingInterval: 30000, requireHostHeader: true, joinDuplicateHeaders: undefined, rejectNonStandardBodyWrites: false, _events: [Object: null prototype], _eventsCount: 3, _maxListeners: undefined, _connections: 1, _handle: [TCP], _usingWorkers: false, _workers: [], _unref: false, _listeningId: 2, allowHalfOpen: true, pauseOnConnect: false, noDelay: true, keepAlive: false, keepAliveInitialDelay: 0, highWaterMark: 16384, httpAllowHalfOpen: false, timeout: 0, maxHeadersCount: null, maxRequestsPerSocket: 0, _connectionKey: '6::::8888', [Symbol(IncomingMessage)]: [Function: IncomingMessage], [Symbol(ServerResponse)]: [Function: ServerResponse], [Symbol(shapeMode)]: false, [Symbol(kCapture)]: false, [Symbol(async_id_symbol)]: 245, [Symbol(kUniqueHeaders)]: null, [Symbol(http.server.connections)]: ConnectionsList {}, [Symbol(http.server.connectionsCheckingInterval)]: Timeout { _idleTimeout: 30000, _idlePrev: [TimersList], _idleNext: [TimersList], _idleStart: 191, _onTimeout: [Function: bound checkConnections], _timerArgs: undefined, _repeat: 30000, _destroyed: false, [Symbol(refed)]: false, [Symbol(kHasPrimitive)]: false, [Symbol(asyncId)]: 248, [Symbol(triggerId)]: 246 } }, _server: Server { maxHeaderSize: undefined, insecureHTTPParser: undefined, requestTimeout: 300000, headersTimeout: 60000, keepAliveTimeout: 5000, connectionsCheckingInterval: 30000, requireHostHeader: true, joinDuplicateHeaders: undefined, rejectNonStandardBodyWrites: false, _events: [Object: null prototype], _eventsCount: 3, _maxListeners: undefined, _connections: 1, _handle: [TCP], _usingWorkers: false, _workers: [], _unref: false, _listeningId: 2, allowHalfOpen: true, pauseOnConnect: false, noDelay: true, keepAlive: false, keepAliveInitialDelay: 0, highWaterMark: 16384, httpAllowHalfOpen: false, timeout: 0, maxHeadersCount: null, maxRequestsPerSocket: 0, _connectionKey: '6::::8888', [Symbol(IncomingMessage)]: [Function: IncomingMessage], [Symbol(ServerResponse)]: [Function: ServerResponse], [Symbol(shapeMode)]: false, [Symbol(kCapture)]: false, [Symbol(async_id_symbol)]: 245, [Symbol(kUniqueHeaders)]: null, [Symbol(http.server.connections)]: ConnectionsList {}, [Symbol(http.server.connectionsCheckingInterval)]: Timeout { _idleTimeout: 30000, _idlePrev: [TimersList], _idleNext: [TimersList], _idleStart: 191, _onTimeout: [Function: bound checkConnections], _timerArgs: undefined, _repeat: 30000, _destroyed: false, [Symbol(refed)]: false, [Symbol(kHasPrimitive)]: false, [Symbol(asyncId)]: 248, [Symbol(triggerId)]: 246 } }, parser: HTTPParser { '0': null, '1': [Function: parserOnHeaders], '2': [Function: parserOnHeadersComplete], '3': [Function: parserOnBody], '4': [Function: parserOnMessageComplete], '5': [Function: bound onParserExecute], '6': [Function: bound onParserTimeout], _headers: [], _url: '', socket: [Circular *1], incoming: [Circular *2], outgoing: null, maxHeaderPairs: 2000, _consumed: true, onIncoming: [Function: bound parserOnIncoming], joinDuplicateHeaders: null, [Symbol(resource_symbol)]: [HTTPServerAsyncResource] }, on: [Function: socketListenerWrap], addListener: [Function: socketListenerWrap], prependListener: [Function: socketListenerWrap], setEncoding: [Function: socketSetEncoding], _paused: false, _httpMessage: ServerResponse { _events: [Object: null prototype], _eventsCount: 1, _maxListeners: undefined, outputData: [], outputSize: 0, writable: true, destroyed: false, _last: false, chunkedEncoding: false, shouldKeepAlive: true, maxRequestsOnConnectionReached: false, _defaultKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: true, _removedConnection: false, _removedContLen: false, _removedTE: false, strictContentLength: false, _contentLength: null, _hasBody: true, _trailer: '', finished: false, _headerSent: false, _closed: false, socket: [Circular *1], _header: null, _keepAliveTimeout: 5000, _onPendingData: [Function: bound updateOutgoingData], req: [Circular *2], _sent100: false, _expect_continue: false, _maxRequestsPerSocket: 0, [Symbol(shapeMode)]: false, [Symbol(kCapture)]: false, [Symbol(kBytesWritten)]: 0, [Symbol(kNeedDrain)]: false, [Symbol(corked)]: 0, [Symbol(kOutHeaders)]: [Object: null prototype], [Symbol(errored)]: null, [Symbol(kHighWaterMark)]: 16384, [Symbol(kRejectNonStandardBodyWrites)]: false, [Symbol(kUniqueHeaders)]: null }, [Symbol(async_id_symbol)]: 250, [Symbol(kHandle)]: TCP { reading: true, onconnection: null, _consumed: true, [Symbol(owner_symbol)]: [Circular *1] }, [Symbol(lastWriteQueueSize)]: 0, [Symbol(timeout)]: null, [Symbol(kBuffer)]: null, [Symbol(kBufferCb)]: null, [Symbol(kBufferGen)]: null, [Symbol(shapeMode)]: true, [Symbol(kCapture)]: false, [Symbol(kSetNoDelay)]: true, [Symbol(kSetKeepAlive)]: false, [Symbol(kSetKeepAliveInitialDelay)]: 0, [Symbol(kBytesRead)]: 0, [Symbol(kBytesWritten)]: 0 }, httpVersionMajor: 1, httpVersionMinor: 1, httpVersion: '1.1', complete: false, rawHeaders: [ 'Host', 'localhost:8888', 'Connection', 'keep-alive', 'Content-Length', '45', 'sec-ch-ua-platform', '"Windows"', 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36', 'Accept', 'application/json, text/plain, */*', 'sec-ch-ua', '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"', 'Content-Type', 'application/json', 'X-Custom-Header', 'foobar', 'sec-ch-ua-mobile', '?0', 'Origin', 'http://localhost:5173', 'Sec-Fetch-Site', 'same-site', 'Sec-Fetch-Mode', 'cors', 'Sec-Fetch-Dest', 'empty', 'Referer', 'http://localhost:5173/', 'Accept-Encoding', 'gzip, deflate, br, zstd', 'Accept-Language', 'zh-CN,zh;q=0.9' ], rawTrailers: [], joinDuplicateHeaders: null, aborted: false, upgrade: false, url: '/Login', method: 'POST', statusCode: null, statusMessage: null, client: <ref *1> Socket { connecting: false, _hadError: false, _parent: null, _host: null, _closeAfterHandlingError: false, _events: { close: [Array], error: [Function: socketOnError], prefinish: undefined, finish: undefined, drain: [Function: bound socketOnDrain], data: [Function: bound socketOnData], end: [Array], readable: undefined, timeout: [Function: socketOnTimeout], resume: [Function: onSocketResume], pause: [Function: onSocketPause] }, _readableState: ReadableState { highWaterMark: 16384, buffer: [], bufferIndex: 0, length: 0, pipes: [], awaitDrainWriters: null, [Symbol(kState)]: 193997060 }, _writableState: WritableState { highWaterMark: 16384, length: 0, corked: 0, onwrite: [Function: bound onwrite], writelen: 0, bufferedIndex: 0, pendingcb: 0, [Symbol(kState)]: 17564420, [Symbol(kBufferedValue)]: null }, allowHalfOpen: true, _maxListeners: undefined, _eventsCount: 8, _sockname: null, _pendingData: null, _pendingEncoding: '', server: Server { maxHeaderSize: undefined, insecureHTTPParser: undefined, requestTimeout: 300000, headersTimeout: 60000, keepAliveTimeout: 5000, connectionsCheckingInterval: 30000, requireHostHeader: true, joinDuplicateHeaders: undefined, rejectNonStandardBodyWrites: false, _events: [Object: null prototype], _eventsCount: 3, _maxListeners: undefined, _connections: 1, _handle: [TCP], _usingWorkers: false, _workers: [], _unref: false, _listeningId: 2, allowHalfOpen: true, pauseOnConnect: false, noDelay: true, keepAlive: false, keepAliveInitialDelay: 0, highWaterMark: 16384, httpAllowHalfOpen: false, timeout: 0, maxHeadersCount: null, maxRequestsPerSocket: 0, _connectionKey: '6::::8888', [Symbol(IncomingMessage)]: [Function: IncomingMessage], [Symbol(ServerResponse)]: [Function: ServerResponse], [Symbol(shapeMode)]: false, [Symbol(kCapture)]: false, [Symbol(async_id_symbol)]: 245, [Symbol(kUniqueHeaders)]: null, [Symbol(http.server.connections)]: ConnectionsList {}, [Symbol(http.server.connectionsCheckingInterval)]: Timeout { _idleTimeout: 30000, _idlePrev: [TimersList], _idleNext: [TimersList], _idleStart: 191, _onTimeout: [Function: bound checkConnections], _timerArgs: undefined, _repeat: 30000, _destroyed: false, [Symbol(refed)]: false, [Symbol(kHasPrimitive)]: false, [Symbol(asyncId)]: 248, [Symbol(triggerId)]: 246 } }, _server: Server { maxHeaderSize: undefined, insecureHTTPParser: undefined, requestTimeout: 300000, headersTimeout: 60000, keepAliveTimeout: 5000, connectionsCheckingInterval: 30000, requireHostHeader: true, joinDuplicateHeaders: undefined, rejectNonStandardBodyWrites: false, _events: [Object: null prototype], _eventsCount: 3, _maxListeners: undefined, _connections: 1, _handle: [TCP], _usingWorkers: false, _workers: [], _unref: false, _listeningId: 2, allowHalfOpen: true, pauseOnConnect: false, noDelay: true, keepAlive: false, keepAliveInitialDelay: 0, highWaterMark: 16384, httpAllowHalfOpen: false, timeout: 0, maxHeadersCount: null, maxRequestsPerSocket: 0, _connectionKey: '6::::8888', [Symbol(IncomingMessage)]: [Function: IncomingMessage], [Symbol(ServerResponse)]: [Function: ServerResponse], [Symbol(shapeMode)]: false, [Symbol(kCapture)]: false, [Symbol(async_id_symbol)]: 245, [Symbol(kUniqueHeaders)]: null, [Symbol(http.server.connections)]: ConnectionsList {}, [Symbol(http.server.connectionsCheckingInterval)]: Timeout { _idleTimeout: 30000, _idlePrev: [TimersList], _idleNext: [TimersList], _idleStart: 191, _onTimeout: [Function: bound checkConnections], _timerArgs: undefined, _repeat: 30000, _destroyed: false, [Symbol(refed)]: false, [Symbol(kHasPrimitive)]: false, [Symbol(asyncId)]: 248, [Symbol(triggerId)]: 246 } }, parser: HTTPParser { '0': null, '1': [Function: parserOnHeaders], '2': [Function: parserOnHeadersComplete], '3': [Function: parserOnBody], '4': [Function: parserOnMessageComplete], '5': [Function: bound onParserExecute], '6': [Function: bound onParserTimeout], _headers: [], _url: '', socket: [Circular *1], incoming: [Circular *2], outgoing: null, maxHeaderPairs: 2000, _consumed: true, onIncoming: [Function: bound parserOnIncoming], joinDuplicateHeaders: null, [Symbol(resource_symbol)]: [HTTPServerAsyncResource] }, on: [Function: socketListenerWrap], addListener: [Function: socketListenerWrap], prependListener: [Function: socketListenerWrap], setEncoding: [Function: socketSetEncoding], _paused: false, _httpMessage: ServerResponse { _events: [Object: null prototype], _eventsCount: 1, _maxListeners: undefined, outputData: [], outputSize: 0, writable: true, destroyed: false, _last: false, chunkedEncoding: false, shouldKeepAlive: true, maxRequestsOnConnectionReached: false, _defaultKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: true, _removedConnection: false, _removedContLen: false, _removedTE: false, strictContentLength: false, _contentLength: null, _hasBody: true, _trailer: '', finished: false, _headerSent: false, _closed: false, socket: [Circular *1], _header: null, _keepAliveTimeout: 5000, _onPendingData: [Function: bound updateOutgoingData], req: [Circular *2], _sent100: false, _expect_continue: false, _maxRequestsPerSocket: 0, [Symbol(shapeMode)]: false, [Symbol(kCapture)]: false, [Symbol(kBytesWritten)]: 0, [Symbol(kNeedDrain)]: false, [Symbol(corked)]: 0, [Symbol(kOutHeaders)]: [Object: null prototype], [Symbol(errored)]: null, [Symbol(kHighWaterMark)]: 16384, [Symbol(kRejectNonStandardBodyWrites)]: false, [Symbol(kUniqueHeaders)]: null }, [Symbol(async_id_symbol)]: 250, [Symbol(kHandle)]: TCP { reading: true, onconnection: null, _consumed: true, [Symbol(owner_symbol)]: [Circular *1] }, [Symbol(lastWriteQueueSize)]: 0, [Symbol(timeout)]: null, [Symbol(kBuffer)]: null, [Symbol(kBufferCb)]: null, [Symbol(kBufferGen)]: null, [Symbol(shapeMode)]: true, [Symbol(kCapture)]: false, [Symbol(kSetNoDelay)]: true, [Symbol(kSetKeepAlive)]: false, [Symbol(kSetKeepAliveInitialDelay)]: 0, [Symbol(kBytesRead)]: 0, [Symbol(kBytesWritten)]: 0 }, _consuming: false, _dumped: false, [Symbol(shapeMode)]: true, [Symbol(kCapture)]: false, [Symbol(kHeaders)]: { host: 'localhost:8888', connection: 'keep-alive', 'content-length': '45', 'sec-ch-ua-platform': '"Windows"', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36', accept: 'application/json, text/plain, */*', 'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"', 'content-type': 'application/json', 'x-custom-header': 'foobar', 'sec-ch-ua-mobile': '?0', origin: 'http://localhost:5173', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', referer: 'http://localhost:5173/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'zh-CN,zh;q=0.9' }, [Symbol(kHeadersCount)]: 34, [Symbol(kTrailers)]: null, [Symbol(kTrailersCount)]: 0 }
原生node.js接收前端數據
//接收數據 let body = ''; // 每次接收到一部分數據,就累加到 body req.on('data', chunk => { body += chunk.toString(); }); // 數據接收完畢后,在這里處理完整的 body req.on('end', () => { //解析JSON格式 try { const data = JSON.parse(body); console.log('接收到的數據:', data); res.end('ok'); } catch (err) { console.error('解析失敗:', err); res.statusCode = 400; res.end('Invalid JSON'); } });
req.on
在 Node.js 的 HTTP 服務器處理中,`req.on` 用于監聽 HTTP 請求對象 (`IncomingMessage`) 的事件。`req` 是一個繼承了 `EventEmitter` 類的對象,可以通過 `.on()` 方法監聽各種請求相關的事件。 以下是常見的 `req.on` 使用場景和詳細解釋: --- ### 1. **接收請求體數據(POST/PUT 等)** 當客戶端通過 POST 或 PUT 方法發送數據時,數據會被分成多個 **chunk(數據塊)** 傳輸。你需要監聽 `'data'` 和 `'end'` 事件來完整接收數據。 ```javascript const http = require('http'); const server = http.createServer((req, res) => { let body = []; // 監聽 'data' 事件:每次接收到數據塊時觸發 req.on('data', (chunk) => { body.push(chunk); // 將數據塊存入數組 }); // 監聽 'end' 事件:所有數據接收完成后觸發 req.on('end', () => { body = Buffer.concat(body).toString(); // 合并所有數據塊 console.log('Received body:', body); res.end('Data received'); }); }); server.listen(3000); ``` - **為什么需要這樣處理?** HTTP 請求體可能很大,Node.js 以流(Stream)的形式逐步傳輸數據,避免內存溢出。 --- ### 2. **處理請求錯誤** 監聽 `'error'` 事件可以捕獲請求過程中發生的錯誤(如客戶端提前斷開連接)。 ```javascript req.on('error', (err) => { console.error('Request error:', err); // 可以在此處關閉連接或清理資源 }); ``` --- ### 3. **其他事件** - **`'close'`**: 當底層連接關閉時觸發。 - **`'aborted'`**: 當請求被客戶端中止時觸發。 --- ### 4. **注意事項** - **必須監聽 `'data'` 才會觸發 `'end'`** 如果你不監聽 `'data'` 事件,流會處于 **暫停模式**,`'end'` 事件永遠不會觸發。 - **流(Stream)的工作模式** - **流動模式(Flowing Mode)**: 通過 `.on('data')` 自動接收數據。 - **暫停模式(Paused Mode)**: 需要手動調用 `.read()` 讀取數據。 - **框架的封裝** 在 Express 或 Koa 等框架中,通常使用中間件(如 `body-parser`)自動處理請求體數據,無需手動監聽 `'data'` 和 `'end'`。 --- ### 5. **完整示例** ```javascript const http = require('http'); const server = http.createServer((req, res) => { let data = ''; req.on('data', (chunk) => { data += chunk; // 拼接數據塊(字符串形式) }); req.on('end', () => { try { const jsonData = JSON.parse(data); // 解析 JSON 數據 res.end('Data processed'); } catch (err) { res.statusCode = 400; res.end('Invalid JSON'); } }); req.on('error', (err) => { console.error('Request error:', err); res.statusCode = 500; res.end('Internal Server Error'); }); }); server.listen(3000, () => { console.log('Server running on port 3000'); }); ``` --- ### 6. **Express 中的對比** 在 Express 中,使用 `express.json()` 中間件后,可以直接通過 `req.body` 獲取解析后的數據,無需手動監聽事件: ```javascript const express = require('express'); const app = express(); app.use(express.json()); // 自動處理 JSON 請求體 app.post('/', (req, res) => { console.log(req.body); // 直接訪問解析后的數據 res.send('Data received'); }); app.listen(3000); ``` --- ### 總結 - **`req.on`** 用于監聽 HTTP 請求對象的事件,適用于原始 Node.js 環境。 - 主要事件:`data`(接收數據塊)、`end`(數據接收完成)、`error`(處理錯誤)。 - 在框架中(如 Express),通常有更簡潔的封裝,無需直接操作這些事件。