Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify port number in HTTP request (node.js)

Is it possible to specify a port number when making at HTTP request using the request module? I'm not seeing anything about this in the documentation:

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) {
  // ...
});

Additionally, when I run the second version, absolutely nothing happens in my program (almost like the request was never made).

I also know that I can specify a port number when making a request using the core http module. Why is the not an option in the request module?

EDIT: I should have mentioned this before, but I am running this application on Heroku.

When I run the request locally (using the request module) I am able to specify the port number, and get a successful callback.

When I run the request from Heroku, no callback is fired, and nginx shows no record of the request.

Am I crazy? Is there some reason Heroku is preventing me from making an outbound HTTP request to a specific port number?

like image 944
djfdev Avatar asked Jul 27 '15 20:07

djfdev


2 Answers

Using request with the complete URL as the first argument works for me:

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

Specifying the method and the url separately also works:

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

You might want to check that your server is running and that you're not behind a proxy or firewall that prevents access on that port.

like image 197
Robin Murphy Avatar answered Oct 01 '22 04:10

Robin Murphy


I realize the question asks for the request module but in a more general context, if using the http module, you can use the port key docs.

e.g.

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)
})
like image 27
Mauro Moreno Avatar answered Oct 01 '22 04:10

Mauro Moreno