【问题标题】:How to send GET request without downloading response content using node-requests?如何在不使用节点请求下载响应内容的情况下发送 GET 请求?
【发布时间】:2019-07-13 10:26:51
【问题描述】:

我目前正在学习节点,我正在寻找允许我发送 GET 请求而无需下载服务器响应内容(正文)的 HTTP 库。

我需要每分钟发送大量的 http 请求。但是我不需要阅读他们的内容(也可以节省带宽)。我不能将 HEAD 用于此目的。

有什么方法可以避免使用节点请求或任何其他库下载响应正文 - 可以使用吗?

我使用节点请求的示例代码:

const options = {
    url: "https://google.com",
    headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
    }
}

//How to avoid downloading a whole response?

function callback(err, response, body) {
    console.log(response.request.uri.host + '   -   ' + response.statusCode);
}

request(options, callback);

【问题讨论】:

    标签: javascript node.js http node-request


    【解决方案1】:

    HTTP GET 按标准获取文件内容,您无法避免下载(获得响应)它,但您可以忽略它。这基本上就是你正在做的事情。

    request(options, (err, response, body)=>{
       //just return from here don't need to process anything
    });
    

    EDIT1: 要仅使用响应的某些字节,您可以使用 http.get 并使用 data 事件获取数据。来自doc

    http.get('http://nodejs.org/dist/index.json', (res) => {
    
      res.setEncoding('utf8');
      let rawData = '';
      res.on('data', (chunk) => { rawData += chunk; });
      res.on('end', () => {
        //this is when the response will end
      });
    
    }).on('error', (e) => {
      console.error(`Got error: ${e.message}`);
    });
    

    【讨论】:

    • 您可以只读取第一个块,然后通过关闭连接忽略其余部分。我知道可以使用不同的语言(例如 python 请求)来避免下载正文并仅获取响应标头。我希望在节点中实现类似的目标。
    • 然后使用http.get 并添加data 事件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多