0

can we replicate curl resolve host in node-fetch or any other node http library.

curl https://www.example.net --resolve www.example.net:443:127.0.0.1

Faizan Ahmed
  • 184
  • 3
  • 12

1 Answers1

1

You don't need another lib to do this. The builtin http module works fine:

const http = require('http');

const options = {
  hostname: '2606:2800:220:1:248:1893:25c8:1946',
  port: 80,
  path: '/',
  method: 'GET',
  headers: {
    'Host': 'example.com'
  }
};

const req = http.request(options, (res) => {
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.end();

In HTTP protocol, the host name is in headers, and the IP used to establish the TCP connection is independent from that.

harttle
  • 88
  • 1
  • 12
  • Error: connect ETIMEDOUT at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16) Emitted 'error' event on ClientRequest instance at: at Socket.socketErrorListener (node:_http_client:447:9) at Socket.emit (node:events:390:28) at emitErrorNT (node:internal/streams/destroy:157:8) at emitErrorCloseNT (node:internal/streams/destroy:122:3) at processTicksAndRejections (node:internal/process/task_queues:83:21) { errno: -4039, code: 'ETIMEDOUT', syscall: 'connect', address: '' port: 80 } Its giving this error – Faizan Ahmed Dec 24 '21 at 08:28
  • your server is https, please `require('https')` and connect to 443 port (by default), refer to https://nodejs.org/api/https.html – harttle Dec 24 '21 at 14:45