node.js - 从 node.js 的 http.IncomingMessage 获取请求正文

标签 node.js httprequest httpserver

我正在尝试为用 node.js 编写的应用程序实现一个简单的 HTTP 端点。我已经创建了 HTTP 服务器,但现在我一直在阅读请求内容正文:

http.createServer(function(r, s) {
    console.log(r.method, r.url, r.headers);
    console.log(r.read());
    s.write("OK"); 
    s.end(); 
}).listen(42646);

请求的方法、URL 和 header 打印正确,但 r.read() 始终为 NULL。我可以说这不是请求的问题,因为 content-length header 在服务器端大于零。

Documentation says r 是一个 http.IncomingMessage 对象,实现了 Readable Stream 接口(interface),那为什么不起作用呢?

最佳答案

“可读”事件错误,它错误地在正文字符串的末尾添加了一个额外的空字符

使用“数据”事件处理带有 block 的流:

http.createServer((r, s) => {
    console.log(r.method, r.url, r.headers);
    let body = '';
    r.on('data', (chunk) => {
        body += chunk;
    });
    r.on('end', () => {
        console.log(body);
        s.write('OK'); 
        s.end(); 
    });
}).listen(42646); 

关于node.js - 从 node.js 的 http.IncomingMessage 获取请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31006711/

相关文章:

api - 流式 API 与 Rest API?

node.js - Jenkins : npm install fail without sudo

node.js - Firebase 函数 : How to maintain 'app-global' API client?

node.js - "Synchronous XMLHttpRequest on the main thread is deprecated"使用 nodejs app.get 或 http-server

c - C 中的 HTTP GET 服务器,长时间等待 (TTFB)

linux - Goroutine长时间处于IO等待状态

javascript - Next.js : Refresh page after modifying a file, 无需重新运行 'npm run'

java - 从 HTTP 请求中获取完整路径

php - php 中的 cfhttp "POST"

java - 在struts 2中上传视频