【问题标题】:Can I get the full http response text in nodejs from a http module .get response?我可以从 http 模块 .get 响应中获取 nodejs 中的完整 http 响应文本吗?
【发布时间】:2022-01-10 04:41:48
【问题描述】:

我有一个非常简单的网络服务器:

const ws = require('http');

ws.createServer(
    function(req,res)
    {
        console.log('request received');
        res.write('Hello world');
        res.end();
    })
    .listen(1234);

服务器正常工作。当我在 localhost:1234 上打开浏览器时,我得到 Hello World 文本。当我从 REST 客户端向 localhost:1234 发送 GET 时,我得到:

HTTP/1.1 200 OK
Date: Fri, 03 Dec 2021 20:10:12 GMT
Connection: close
Transfer-Encoding: chunked

Hello world

现在,我想编写一个测试,但我无法找到从响应中提取“Hello world”文本的任何方法。目前,我的测试代码如下所示:

const http = require('http');

let req = http.get('http://localhost:1234',(res)=>{
    let txt = res.read();
    console.log(txt);
});

这总是返回 null。

我也试过了:

const http = require('http');

let req = http.get('http://localhost:1234',(res)=>{
    let data = [];
    res.on('data',(chunk)=>data.push(chunk));
    console.log(data);
});

这会返回一个空数组。

当我调试并查看 res 对象时,很容易在响应中找到除 Hello World 文本之外的所有内容(主要在 res.headers 中)。我已经看到很多例子来提取以 JSON 格式发送的数据等,但我想从最简单的例子(只是纯文本)开始,似乎找不到任何方法来做到这一点。当我通过 HTTP 模块发送 GET 时,似乎浏览器可以返回的任何东西应该可用,但我找不到它。

【问题讨论】:

    标签: javascript node.js http webserver


    【解决方案1】:

    您可以通过这种方式将响应读取为 json:

    服务器文件:

    const ws = require('http');
    
    ws.createServer(
      (request, response) => {
    
        console.log('request received');
    
        response.write('{"body": "Hello World !"}');
        response.end();
    
      }
    ).listen(1234);
    

    请求文件:

    const http = require('http');
    
    http.get('http://localhost:1234', (response) => {
    
      response.on("data", (chunk) => {
    
        body = JSON.parse(chunk).body
    
        console.log(body); // return 'Hello World !' as text
      })
    
    }).on('error', function(e) {
      console.log("Error message : " + e.message);
    });
    

    【讨论】:

    • 谢谢 - 我在互联网上看到很多这样的例子,但我不能假设任何请求都会返回 JSON。我真的很想看到完整的响应(不仅仅是格式化为 JSON 的部分),最好不要更改服务器上的任何内容(因为当我从 REST 客户端获取时,服务器确实给出了预期的响应)。
    【解决方案2】:

    我设法弄明白了。好吧。我发现了一些有用的东西,但仍然不完全理解它的机制。

    以下作品和日志

    世界你好

    到控制台。

    const http = require('http');
    let req = http.get('http://localhost:1234',async (res)=>{
        res.on('readable', () => {
            let txt=res.read().toString();
            console.log(txt);
        });
    });
    

    似乎您需要侦听可读事件才能从 read() 中获取任何内容,并且当您这样做时确实会带回 Hello world 文本(虽然是一个 Buffer 数组,所以需要 ToString() )。

    同样,以下内容也适用于“数据”事件:

    const http = require('http');
    
    let req = http.get('http://localhost:1234',(res)=>{
        let txt = '';
        res.on('data',(chunk)=>{
            txt+=chunk.toString();
            console.log(txt);
        });
    });
    

    我有一些后续问题,但如果我不明白,我会做更多研究并在新问题中再次提问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      相关资源
      最近更新 更多