Node.js 是否可以通过另一个IP通过打捆针模块发送请求?
请求模块具有参数localAddressNode.js 是否可以通过另一个IP通过打捆针模块发送请求?,node.js,http,request,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'
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){}
如何使用needle模块?needle仍然是
请求
等节点的包装器,但needle
不允许您专门传递本地地址
,也不允许将任意选项传递给
针不支持为请求添加自定义,并且该方法支持在使用
设置有点复杂,但可以覆盖默认行为
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()
})
Pinele仍然是像
request
这样的节点的包装器,但是Pinele
不允许您专门传递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()
})