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),通常有更简洁的封装,无需直接操作这些事件。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/diannao/81332.shtml
繁体地址,请注明出处:http://hk.pswp.cn/diannao/81332.shtml
英文地址,请注明出处:http://en.pswp.cn/diannao/81332.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

计算机网络01-网站数据传输过程

局域网&#xff1a; 覆盖范围小&#xff0c;自己花钱买设备&#xff0c;宽带固定&#xff0c;自己维护&#xff0c;&#xff0c;一般长度不超过100米&#xff0c;&#xff0c;&#xff0c;带宽也比较固定&#xff0c;&#xff0c;&#xff0c;10M&#xff0c;&#xff0c;&…

Mysql常用函数解析

字符串函数 CONCAT(str1, str2, …) 将多个字符串连接成一个字符串。 SELECT CONCAT(Hello, , World); -- 输出: Hello World​​SUBSTRING(str, start, length) 截取字符串的子串&#xff08;起始位置从1开始&#xff09;。 SELECT SUBSTRING(MySQL, 3, 2); -- 输出: SQ…

SpringMVC 前后端数据交互 中文乱码

ajax 前台传入数据&#xff0c;但是后台接收到的数据中文乱码 首先我们分析一下原因&#xff1a;我们调用接口的时候传入的中文&#xff0c;是没有乱码的 此时我们看一下Java后台接口对应的编码&#xff1a; 默认情况&#xff1a;Servlet容器&#xff08;如Tomcat&#xff09;默…

loads、dumps、jsonpath使用场景

在处理JSON数据时&#xff0c;loads、dumps 和 jsonpath 是三个非常有用的工具或概念。它们各自在不同的场景下发挥作用&#xff0c;让我们一一来看&#xff1a; 1. loads loads 函数是 Python 中 json 模块的一部分&#xff0c;用于将 JSON 格式的字符串解析成 Python 的数据…

Java学习手册:Spring 事务管理

一、事务管理的概念 事务是一组操作的集合&#xff0c;这些操作要么全部成功&#xff0c;要么全部失败。事务管理的目的是保证数据的一致性和完整性。在数据库操作中&#xff0c;事务管理尤为重要&#xff0c;例如银行转账、订单支付等场景都需要事务管理来确保数据的正确性。…

echarts自定义图表--柱状图-横向

区别于纵向表格 xAxis和yAxis对调 要将label全部固定到最右侧&#xff1a; 隐藏一个柱形 为每个label设置固定的偏移距离 offset: [300 - 80, 0] 在data中加入label的配置 根据现在的值生成距离右侧的偏移 更新方法 chart.setOption({series: [{},{data: data.map(v > ({v…

【CV数据集】Visdrone2019无人机目标检测数据集(YOLO、VOC、COCO格式)

visdrone2019的Task1是非常通用的目标检测数据集&#xff0c;也是许多人做目标检测论文和项目必然会用到的数据集&#xff0c;我将该数据集进行了处理&#xff0c;将其YOLO、VOC和COCO格式都整理好&#xff0c;通过下载我整理好的数据集和相关文件&#xff0c;可以直接在自己的…

常见电源的解释说明

英文缩写 BJT&#xff08;bipolar junction transistor&#xff09;双极型结晶体管FET&#xff08;field-effect transistor&#xff09;场效应管TTL&#xff08;Transistor-Transistor Logic&#xff09;三极管CMOS&#xff08;Complementary Metal Oxide Semiconductor&…

【2025年五一数学建模竞赛】A题 解题思路与模型代码

2025年五一数学建模竞赛 A题 问题一&#xff1a;推测支路 1 和支路 2 的车流量 1.1 问题描述 根据提供的主路历史数据以及已知的支路车流量变化趋势&#xff08;支路1呈线性增长&#xff0c;支路2先线性增长后线性减少&#xff09;&#xff0c;推测这两个支路在特定时间段&a…

d202551

目录 一、175. 组合两个表 - 力扣&#xff08;LeetCode&#xff09; 二、511. 游戏玩法分析 I - 力扣&#xff08;LeetCode&#xff09; 三、1204. 最后一个能进入巴士的人 - 力扣&#xff08;LeetCode&#xff09; 一、175. 组合两个表 - 力扣&#xff08;LeetCode&#xf…

RISC-V AIA SPEC学习(四)

第五章 Interrupts for Machine andSupervisor Levels 核心内容​​ 1.主要中断类型与默认优先级:​​ 定义了机器级别(M-level)和监管者级别(S-level)的标准中断类型(如MEI、SEI、MTI等)。默认优先级规则:本地中断(如软件/定时器)优先级高于外部中断,RAS事件(如低/高…

WSGI(Web Server Gateway Interface)服务器

0、什么是 WSGI WSGI &#xff08;Web Server Gateway Interface&#xff09; 是一种Python规范&#xff0c;它定义了 Web 服务器 和 Python Web 应用程序之间的通信接口。 即&#xff0c;能够让各种 Web 服务器&#xff08;如 Nginx、Apache 等&#xff09;和 Python Web 框架…

博客打卡-人类基因序列功能问题动态规划

题目如下&#xff1a; 众所周知&#xff0c;人类基因可以被认为是由4个核苷酸组成的序列&#xff0c;它们简单的由四个字母A、C、G和T表示。生物学家一直对识别人类基因和确定其功能感兴趣&#xff0c;因为这些可以用于诊断人类疾病和设计新药物。 生物学家确定新基因序列功能…

基本功能学习

一.enum枚举使用 E_SENSOR_REQ_NONE 的定义及用途 在传感器驱动开发或者电源管理模块中&#xff0c;E_SENSOR_REQ_NONE通常被用来表示一种特殊的状态或请求模式。这种状态可能用于指示当前没有活动的传感器请求&#xff0c;或者是默认初始化状态下的一种占位符。 可能的定义…

vitest | 测试框架vitest | 总结笔记

目录 测试框架 vitest 介绍 测试文件的写法 文件取名&#xff1a;文件名中要有 test&#xff0c;即 xxx.test.ts 引入库&#xff1a; test 测试&#xff1a; 测试运行&#xff1a; npx test 文件名 &#xff0c;每次保存后会重新运行。 ★ expect 方法&#xff1a; v…

ESP32开发-作为TCP客户端发送数据到网络调试助手

​​代码&#xff08;作为TCP客户端&#xff09;​​ #include <SPI.h> #include <EthernetENC.h> // 使用EthernetENC库// 网络配置 byte mac[] {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; // MAC地址 IPAddress ip(192, 168, 1, 100); // ESP32的IP IPAddr…

HTML5 WebSocket:实现高效实时通讯

一、引言 在当今的 Web 开发领域,实时通讯功能变得越来越重要。例如在线聊天、实时数据更新等场景都需要客户端与服务器之间能够进行高效的双向数据传输。HTML5 引入的 WebSocket 协议为我们提供了一种强大的解决方案,它在单个 TCP 连接上实现了全双工通讯,极大地改善了传统…

速通Ollama本地部署DeepSeek-r1

下载 Ollama 前往 Ollama官网 下载客户端&#xff0c;下载完成后点击Install安装即可。 完成后会自动安装在C:盘的AppData文件夹下&#xff0c;命令行输入ollama后&#xff0c;显示下图中的信息表明安装成功。 下载模型 在官网界面点击 DeepSeek-R1 超链接 跳转到DeepSeek安装…

总结C++中的STL

1.STL 概述 STL 即标准模板库&#xff0c;是 C 标准程序库的重要组成部分&#xff0c;包含常用数据结构和算法&#xff0c;体现了泛型化程序设计思想&#xff0c;基于模板实现&#xff0c;提高了代码的可复用性 2.容器 2.1 序列容器&#xff1a; 1. vector 特性&#xff…

自动驾驶-一位从业两年的独特视角

时间简介 2023.03 作为一名大三学生&#xff0c;加入到某量产车企&#xff0c;从事地图匹配研发 2023.07 地图匹配项目交付&#xff0c;参与离线云端建图研发 2023.10 拿到24届校招offer 2024.07 正式入职 2025.01 离线云端建图稳定&#xff0c;开始接触在线车端融图研发 自动…