【问题标题】:Fetch only headers of a GET request in Node在 Node 中仅获取 GET 请求的标头
【发布时间】:2020-10-09 03:38:03
【问题描述】:

我需要使用 Node 获取 large 文件的 Content-LengthContent-Type 标头。

不幸的是,我正在处理的服务器不允许HEAD 请求,并且文件太大而无法发出整个GET 请求。

我正在寻找类似这样的 python 代码:

import requests

r = requests.get(url, stream=True)
content_length = r.headers['Content-Length']
content_type = r.headers['Content-Type']

stream=True 参数表示文件不会被完全下载。

【问题讨论】:

    标签: node.js http get http-headers


    【解决方案1】:

    如果您使用的是 request 包,您可以执行以下操作:

    const request = require('request');
    const r = request(url);
    r.on('response', response => {
        const contentLength = response.headers['content-length'];
        const contentType = response.headers['content-type'];
        // ...
        r.abort();
    });
    

    【讨论】:

      【解决方案2】:

      nodejs 的 http 库默认不会获取所有内容,但回调将包含 IncomingMessage 对象,以构建您必须监听的完整响应 .on('data')。

      看看:

      https://nodejs.org/api/http.html#http_http_get_options_callback

      如果你想“忽略”传入的数据,你可以调用 res.abort()。调用它会导致响应中剩余的数据被丢弃并销毁套接字。

      【讨论】:

      • 这对我不起作用。在http.get 回调中,我添加了res.on('data', ...),但内部回调没有被调用。我猜它会以整个文件作为块来调用。
      【解决方案3】:

      使用method: 'HEAD':

      http.request('http://example.com', {
          method: 'HEAD',
      }, res => {
          console.log(res.statusCode, res.statusMessage)
          console.log(res.headers)
      
          res.on('data', _ => {
              console.log(`IT SHOULDN'T REACH HERE!`)
          })
      }).on('error', console.error)
        .end()
      

      【讨论】:

      • OP说服务器不支持HEAD
      猜你喜欢
      • 2015-11-26
      • 1970-01-01
      • 2017-11-01
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 2020-10-15
      相关资源
      最近更新 更多