Heroku 上使用 Node.js 的代理服务器

2023-11-22

我正在尝试使用 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/'

我想我错了一些配置,但一整天后我仍然 无法弄清楚。

Update

我继续进行测试,发现代理无法访问代理服务,这完全阻止了我。

在开发中我设置:

  • LOCALHOST = '本地主机'
  • DEVICES_URI = 'lelylan-devices.herokuapp.com/'

如果我打电话http://lelylan-devices.herokuapp.com/devices一切正常。

如果我调用 localhost:8000/devices (它指向http://lelylan-devices.herokuapp.com/devices) Heroku 告诉我没有这样的应用程序。我猜问题出在路由系统上。

在这里您可以访问源代码。 这里是 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

我终于用一个稍微修改过的版本让它工作了按 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);

需要记住的一个注释。该插件将标头 HOST 设置为目标应用程序 uri。如果您不这样做,Heroku 将无法识别该应用程序,也不会找到它,因为其内部路由系统似乎基于 HOST 标头。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Heroku 上使用 Node.js 的代理服务器 的相关文章

随机推荐