javascript - 如何在不使用节点请求下载响应内容的情况下发送 GET 请求?
问题描述
我目前正在学习节点,我正在寻找允许我发送 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);
解决方案
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}`);
});