代码如下:
const http = require('http'); // 换成https同样适用 const dns = require('dns'); function customlookup(hostname, options, callback) { if (typeof options === 'function') { callback = options; options = null; } // todo: check `options` for options like `all` and `family` if (hostname.toLowerCase() === 'www.sample.com') { // 动态绑定IP:www.sample.com=>127.0.0.1 const host = { address: '127.0.0.1', family: 4 // or 6 (IPV6) } return callback(null, host.address, host.family); } return dns.lookup(hostname, options, callback); } http.get({ hostname: 'www.sample.com', lookup: customlookup }, (res) => { console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); res.setEncoding('utf8'); res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); res.on('end', () => { }); });