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

标签 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){}

如何使用针头模块来完成?

最佳答案

Needle 仍然是 Node 的包装器 http.requestrequestneedle 不允许您专门传递 localAddress 或将任意选项传递给 http.request .

Needle 支持添加自定义 http.Agent对于请求和 agent.createConnection方法支持传递 localAddress 因为它使用 standard socket connect .

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

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()
})

关于node.js - 是否可以通过另一个 IP 向 Needle 模块发送请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47255262/

相关文章:

Python - 发送 "Incomplete"GET 请求

node.js - 如何使用 Node.js 中的 fs.createWriteStream() 附加到字符串化的 JSON 数组

javascript - 如何让nodejs在继续之前等待mongodb连接(以阻塞方式调用async)

node.js - 同一项目中两种不同的 Node JS 共存

http - 如何在golang中生成查询字符串?

xml - Perl 通过 HTTP 解析 XML 文件并增加几行

security - 从服务器向客户端发送授权 header 是否安全?

javascript - 使用 mongodb 和 mongoose 更改 Node js 应用程序中搜索查询的输出/投影格式

node.js - Node.js 请求模块中的 IP 地址而不是域名

javascript - HTML 表单发送错误的文件负载