是否有可能通过另一个IP地址发送Needle模块的请求?

请求模块具有参数localAddress。

options = { url: "https://ru.tradeskinsfast.com/ajax/botsinventory", method: "post", headers: { 'accept': 'application/json, text/javascript, */*; q=0.01', 'accept-encoding' : 'gzip :deflate, br', 'accept-language': 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4', }, localAdress: someIp, } request(options, function(error, response, body){} 

我怎样才能做到这一点针模块?

针仍然是一个像request一样的节点http.request的包装,但needle不允许你特别通过localAddress或任意选项传递给http.request

Needle支持为请求添加自定义的http.Agent ,而agent.createConnection方法支持通过localAddress因为它使用标准套接字连接 。

设置更复杂一点,但可以覆盖默认行为。

 const http = require('http') const https = require('https') const needle = require('needle') class HttpAgentLocal extends http.Agent { constructor(options){ super(options) if (options && options.localAddress) this._localAddress = options.localAddress } createConnection(options, callback){ if (this._localAddress) options.localAddress = this._localAddress return super.createConnection(options, callback) } } class HttpsAgentLocal extends https.Agent { constructor(options){ this._localAddress = options.localAddress } createConnection(options, callback){ options.localAddress = this._localAddress return super.createConnection(options, callback) } } let server = http.createServer((req, res) => { console.log('request: %s - %s', req.method,req.url, req.connection.remoteAddress) res.end('hello\n') }) server.listen(3121, async ()=> { console.log('listening') const agent = new HttpAgentLocal({ localAddress: '10.8.8.8' }) let res = await needle('get','http://localhost:3121/', null, { agent: agent }) console.log(res.body.toString()) server.close() })