Specify the port number in the HTTP request (node.js)

Is it possible to specify a port number when making an HTTP request using the request module? I don't see anything 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) {
  // ...
});

      

Also, when I run the second version, absolutely nothing happens in my program (much like the request was never executed).

I also know that when asked, I can specify the port number using the main module http

. Why isn't this an option in the request module?

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

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

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

I've gone crazy? Is there a reason Heroku is preventing me from sending an outbound HTTP request to a specific port number?

+3


source to share


2 answers


Usage request

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

      

The task method

and 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 are not behind a proxy or firewall that prevents access to this port.

+4


source


I understand that the question is asking for a request module, but in a more general context, if you are using an http module, you can use the port

docs key .

eg.



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

      

0


source







All Articles