Node.js 中的数据块
node.jsserver side programmingprogramming更新于 2024/11/9 22:08:00
Node.js 或任何其他语言中的数据块可以定义为客户端发送到所有服务器的数据片段。服务器将这些块组成一个流,并形成一个缓冲流。然后,此缓冲流被转换为有意义的数据。
语法
request.on('eventName', [callback] )
参数
参数如下所述 −
eventName − 它是将要触发的事件的名称。
callback −回调函数用于处理任何错误(如果发生)。
示例
创建一个名为"index.js"的文件并复制以下代码片段。创建文件后,使用命令"node index.js"运行此代码。
// Node 中的数据块示例 // 导入 http 模块 const http = require('http'); // 创建服务器 const server = http.createServer((req, res) => { const url = req.url; const method = req.method; if (url === '/') { // 定义 HTML 页面 res.write('<html>'); res.write('<head><title>Enter Message</title><head>'); res.write(`<body><form action="/message" method="POST"> <input type="text" name="message"></input> <button type="submit">Send</button></form></body></html>`); res.write('</html>'); return res.end(); } // POST 请求发送数据 if (url === '/message' && method === 'POST') { const body = []; req.on('data', (chunk) => { // 在服务器上保存块数据 body.push(chunk); console.log(body) }); req.on('end', () => { // 解析缓冲区中的块数据 const parsedBody = Buffer.concat(body).toString(); const message = parsedBody.split('=')[1]; // 打印数据 console.log(message); }); res.statusCode = 302; res.setHeader('Location', '/'); return res.end(); } }); // 启动服务器 server.listen(3000);
输出
C:\home
ode>> node index.js [ <Buffer 6d 65 73 73 61 67 65 3d 57 65 6c 63 6f 6d 65 2b 74 6f 2b 54 75 74 6f 72 69 61 6c 73 2b 50 6f 69 6e 74 2b 25 32 31 25 32 31 25 32 31> ] Welcome+to+Tutorials+Point+%21%21%21