是否可以通过另一个IP向Needle模块发送请求?

时间:2017-11-12 23:42:17

标签: node.js http request

请求模块具有参数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){}

如何使用针模块进行操作?

1 个答案:

答案 0 :(得分:0)

Needle仍然是request之类的节点http.request的包装,但needle不允许您专门传递localAddress或将任意选项传递给{{3} }}

Needle确实支持为请求添加自定义http.request,而http.Agent方法支持在localAddress使用agent.createConnection时传递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() })

设置有点复杂但可以覆盖默认行为。

do while