在HTTP请求中指定端口号(node.js)

djf*_*dev 9 http request node.js

使用请求模块进行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) {
  // ...
});
Run Code Online (Sandbox Code Playgroud)

另外,当我运行第二个版本时,我的程序中绝对没有任何事情发生(几乎就像从未提出过请求).

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

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

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

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

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

小智 8

我意识到这个问题要求请求模块,但在更一般的情况下,如果使用 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)
})
Run Code Online (Sandbox Code Playgroud)


小智 8

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

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();
});
Run Code Online (Sandbox Code Playgroud)

指定methodurl单独也有效:

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();
});
Run Code Online (Sandbox Code Playgroud)

您可能想要检查您的服务器是否正在运行,以及您是否位于阻止该端口访问的代理或防火墙后面.