我正在尝试使用 http-proxy 在 Heroku 上使用 Node.js 构建代理服务器。 在本地一切正常,但我在 Heroku 上遇到了一些问题。
var http = require('http');
var httpProxy = require('http-proxy');
settings = {
"localhost": process.env.LOCALHOST,
"devices": process.env.DEVICES_URI
}
var options = { router: { } }
options.router[settings.localhost + '/devices'] = settings.devices + '/devices';
var port = process.env.PORT || 8000;
var server = httpProxy.createServer(options).listen(port);
如您所见,我在示例中设置了一个路由对象。我要说的是: 当请求匹配 '/devices' 时,然后将请求路由到设备服务。 (由 DEVICES_URI 环境变量标识)
在开发中我设置
- LOCALHOST = '本地主机'
- DEVICES_URI = 'http://localhost:3000'
这意味着所有发送到 localhost:8000/devices 的请求都被代理到 localhost:3000/devices 这就是我想要的。一切都完美无缺。
问题出在生产中。它给我一个重复多次的超时错误 对于每个请求。
2012-08-23T20:18:20+00:00 heroku[router]: Error H12 (Request timeout) -> GET lelylan-api.herokuapp.com/devices dyno=web.1 queue= wait= service=30000ms status=503 bytes=0
在生产环境中,环境变量被配置为应用名称。
- LOCALHOST = 'lelylan-api.herokuapp.com'
- DEVICES_URI = 'lelylan-devices.herokuapp.com/'
我想我错了一些配置,但一整天后我仍然 想不通。
更新
我继续进行测试,发现代理无法访问代理服务,这完全阻止了我。
在开发中我设置:
- LOCALHOST = '本地主机'
- DEVICES_URI = 'lelylan-devices.herokuapp.com/'
如果我调用 http://lelylan-devices.herokuapp.com/devices一切正常。
如果我调用 localhost:8000/devices(指向 http://lelylan-devices.herokuapp.com/devices),Heroku 告诉我没有这样的应用程序。我想问题出在路由系统中。
在这里您可以访问 source code . 这里是 Heroku 的配置变量。
NODE_ENV => production
LOCALHOST => lelylan-api.herokuapp.com
DEVICES_URI => lelylan-devices.herokuapp.com
TYPES_URI => lelylan-types.herokuapp.com
LOCATIONS_URI => lelylan-locations.herokuapp.com
最佳答案
我终于使用稍微修改过的版本让它工作了 proxy-by-url .最终代码看起来像这样并且工作正常。
var httpProxy = require('http-proxy');
var port = process.env.PORT || 8000;
var routing = {
'/devices': { port: process.env.DEVICES_PORT || 80, host: process.env.DEVICES_URI }
}
var server = httpProxy.createServer(
require('./lib/uri-middleware')(routing)
).listen(port);
记住一个注意事项。该插件将 header HOST 设置为目标应用程序 uri。如果您不这样做,Heroku 将无法识别并找到该应用程序,因为它的内部路由系统似乎是基于 HOST header 的。
关于node.js - 在 Heroku 上使用 Node.js 的代理服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12096528/