可能的原因是Heroku的安全策略会阻止远程连接。为了解决这个问题,需要使用Heroku的环境变量来配置允许的远程URL。
具体步骤如下:
添加请求依赖项
npm i request --save
在代码中使用请求:
var request = require('request');
request('http://example.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
在Heroku应用程序的控制面板中设置环境变量:
heroku config:set ALLOWED_HOSTS=example.com
在代码中使用环境变量来定义允许的主机:
var allowed_hosts = process.env.ALLOWED_HOSTS;
var allowed_hosts_array = allowed_hosts.split(',');
var options = { method: 'GET',
url: 'http://example.com',
headers:
{ 'cache-control': 'no-cache' },
json: true };
if(allowed_hosts_array.includes(options.url.hostname)) {
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
} else {
console.log('Request not allowed to ' + options.url.hostname);
}