在HTTP请求(node.js)中指定端口号 [英] Specify port number in HTTP request (node.js)
问题描述
在使用请求模块进行HTTP请求时,是否可以指定端口号?我在文档中什么都没有看到:
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).
我也知道使用核心http
模块发出请求时可以指定端口号.为什么在请求模块中没有该选项?
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?
我之前应该已经提到这一点,但是我正在Heroku上运行此应用程序.
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.
当我从Heroku运行请求时,不会触发任何回调,并且nginx不会显示该请求的记录.
When I run the request from Heroku, no callback is fired, and nginx shows no record of the request.
我疯了吗? Heroku是否有某些原因阻止我向特定端口号发出出站HTTP请求?
Am I crazy? Is there some reason Heroku is preventing me from making an outbound HTTP request to a specific port number?
推荐答案
使用带有完整URL的request
作为第一个参数对我有用:
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();
});
分别指定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();
});
您可能要检查服务器是否正在运行,以及是否没有位于阻止该端口访问的代理或防火墙之后.
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.
这篇关于在HTTP请求(node.js)中指定端口号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!