【问题标题】:Specify port number in HTTP request (node.js)在 HTTP 请求中指定端口号 (node.js)
【发布时间】:2017-03-23 11:09:15
【问题描述】:

是否可以在使用请求模块发出 HTTP 请求时指定端口号?我在文档中没有看到任何关于此的内容:

var request = require('request');

// this works
request({
  method: 'GET',
  url: 'http://example.com'
}, function(error, response, body) {
  if (error) console.log(error);
  console.log(body);
});

// this does not work
request({
  method: 'GET',
  url: 'http://example.com:10080'
}, function(error, response, body) {
  // ...
});

此外,当我运行第二个版本时,我的程序中绝对没有任何反应(几乎就像从未发出过请求一样)。

我也知道我可以在使用核心http 模块发出请求时指定端口号。为什么请求模块中没有选项?

编辑:我之前应该提到过这个,但是我在 Heroku 上运行这个应用程序。

当我在本地运行请求时(使用请求模块),我能够指定端口号,并获得成功的回调。

当我从 Heroku 运行请求时,没有触发回调,并且 nginx 没有显示请求记录。

我疯了吗? Heroku 是否有某些原因阻止我向特定端口号发出出站 HTTP 请求?

【问题讨论】:

  • 您是否尝试运行 wireshark 以确认没有发生任何事情?
  • 否,但我已经使用其他客户端成功发出 HTTP 请求。
  • 所以回调甚至永远不会执行?这似乎很奇怪。
  • 是的,回调永远不会执行。我用更多信息更新了我的帖子。

标签: node.js http request


【解决方案1】:

使用带有完整 URL 的 request 作为第一个参数适用于我:

var http = require('http');
var request = require('request');

// start a test server on some non-standard port
var server = http.createServer(function (req, res) {
  res.end('Hello world');
});
server.listen(1234);

// make the GET request
request('http://127.0.0.1:1234', function (err, res) {
  if (err) return console.error(err.message);

  console.log(res.body);
  // Hello world

  server.close();
});

分别指定method 和url 也可以:

request({
  method: 'GET',
  url: 'http://127.0.0.1:1234'
}, function (err, res) {
  if (err) return console.error(err.message);

  console.log(res.body);
  // Hello world

  server.close();
});

您可能需要检查您的服务器是否正在运行,并且您没有位于阻止访问该端口的代理或防火墙之后。

【讨论】:

    【解决方案2】:

    我知道问题要求请求模块,但在更一般的情况下,如果使用 http 模块,您可以使用 port 键 docs。

    例如

    http.get({
        host: 'example.com', 
        path: '/some/path/',
        port: 8080
    }, function(resp){
        resp.on('data', function(d){
            console.log('data: ' + d)
        })
        resp.on('end', function(){
            console.log('** done **')
        })
    }).on('error', function(err){
        console.log('error ' + err)
    })
    

    【讨论】:

    • 希望找到使用request,而不是核心http 模块的解决方案。
    • 这很有帮助,所以 +1,但我希望我可以直接将端口号放在 URL 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    相关资源
    最近更新 更多