Forked from deepal/custom-http-agent-with-dns-resolve.js
Created
September 11, 2022 07:31
-
-
Save Samjin/166b3f7f0d8c8e55cf06ae0b129ff613 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const dns = require('dns'); | |
const http = require('http'); | |
const https = require('https'); | |
const tls = require('tls'); | |
const net = require('net'); | |
const request = require('request'); | |
const httpAgent = new http.Agent(); | |
const httpsAgent = new https.Agent(); | |
const createConnection = ({ isHttps = false } = {}) => { | |
const connect = isHttps ? tls.connect : net.connect; | |
return function(args, cb) { | |
return connect({ | |
port : args.port, | |
host : args.host, | |
lookup : function(hostname, args, cb) { | |
dns.resolve(hostname, function(err, ips) { | |
if (err) { return cb(err); } | |
return cb(null, ips[0], 4); | |
}); | |
} | |
}, cb); | |
} | |
}; | |
httpAgent.createConnection = createConnection(); | |
httpsAgent.createConnection = createConnection({isHttps: true}); | |
function getRequest(reqUrl) { | |
request({ | |
method: 'get', | |
url: reqUrl, | |
agent: httpsAgent | |
}, (err, res) => { | |
if (err) throw err; | |
console.log(res.body); | |
}) | |
} | |
getRequest('https://example.com'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment