【问题标题】:Conditional port forwarding by hostname按主机名的条件端口转发
【发布时间】:2015-06-10 23:11:26
【问题描述】:

我是node-http-proxy 模块的新手。

我的目标

我需要使用为多子域提供多 SSL 的模块。 例如; 如果用户致电process.localhost:1443,那么我应该将呼叫路由到process.localhost:2443 和 如果用户呼叫api.localhost:1443,那么我应该将呼叫路由到api.localhost:3443

发生了什么

我编写了以下 server.js 代码。但是,当我尝试调用 process.localhost:1443 时,出现以下错误;
D:\Work Space\...\http-proxy\node_modules\requires-port\index.js:13 protocol = protocol.split(':')[0]; TypeError: Cannot call method 'split' of undefined

protocol 看起来像 undefined

function required(port, protocol) {
  protocol = protocol.split(':')[0];

我该怎么办?

server.js

var fs = require('fs'),
    httpProxy = require('http-proxy'),
    express = require('express'),
    app = require('./app').service,
    api = require('./api').service;

// PROXY
var options = {
  changeOrigin: true,
  forward: {
    'process.localhost': 'process.localhost:2443',
    'api.localhost' : 'api.localhost:3443'
  }
}

httpProxy.createServer(options).listen(1443, function() {
  console.log('Proxy is listening on port 1443')
})


// HTTP
app
.listen(2443, function() {
  console.log('PROCESS APP server is listening on port 2443')
})

api
.listen(3443, function() {
  console.log('API APP server is listening on port 3443')
})

【问题讨论】:

  • 首先,您在 httpProxy.createServer 中有一个额外的报价。我也从未见过与 localhost 一起使用的子域
  • 谢谢柏拉图。我以为我应该只有一台服务器来监听1443 端口。然后我可以通过 hostname 分发请求。但我没有使用hostnametargets 还不够吗?
  • 谢谢@apsillers,所以我不应该尝试localhost。我是不是该?我找不到任何其他正确的方式来路由端口。
  • @user3765109 您能否说明您正在运行哪个版本的http-proxy?我查看了github.com/nodejitsu/node-http-proxynpmjs.com/package/http-proxy 上的示例,但它们都没有像您使用它那样使用target。在示例中,target 是字符串或具有 hostport 属性 (target: { host: ..., port: ... }) 的对象,而不是一个主机+端口到另一个的映射。
  • 我找到了另一个遗留示例stackoverflow.com/a/17846415/3765109 我根据最近的http-proxy 代码更新了我的问题。但它不起作用..

标签: node.js routing portforwarding node-http-proxy


【解决方案1】:

我可以通过node-http-proxy论坛的人解决这个问题。

var proxyTable = {}
proxyTable['api.localhost:1443'] = 'http://127.0.0.1:3443'
proxyTable['process.localhost:1443'] = 'http://127.0.0.1:2443'

var proxy = httpProxy.createServer({changeOrigin: true})

var http = require('http')
http.createServer(function(req, res) {

  var options = {
    target: proxyTable[req.headers.host]
  }

  proxy.web(req, res, options)

}).listen(1443, function() {
  console.log('Proxy server is listening on port 1443')
})

app.listen(2443, function() {
  console.log('APP server is listening on port 2443')
})

api.listen(3443, function() {
  console.log('API server is listening on port 3443')
})

【讨论】:

    猜你喜欢
    • 2017-03-14
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多