[英]More elegant way of creating reverse proxy with Node.js
I'm using hapi.js
for serving html content in an application. 我正在使用
hapi.js
在应用程序中提供html内容。 Now I needed to proxy some services which may use websockets. 现在,我需要代理一些可能使用WebSocket的服务。
Here is the working code that proxies http://localhost:4000
in http://localhost:5000/my/app
: 这是在
http://localhost:5000/my/app
中代理http://localhost:4000
的工作代码:
hapi = require "hapi"
http-proxy = require 'http-proxy'
server = hapi.create-server 5000
server.route do
method: '*'
path: '/my/app/{f*}'
handler:
proxy:
map-uri: (request, callback) ->
resourceUri = request.url.path.replace('/my/app/', '/')
url = 'http://localhost:4000' + resourceUri
console.log 'url: ', url
callback(null,url);
pass-through: true
xforward: true
ws-proxy = http-proxy.create-proxy-server do
target:'http://localhost:4000/socket.io/'
ws-proxy.on 'error', (err, req, res) !->
console.log "error caught: ", err#, req
server.start !->
server.listener.on 'upgrade', (req, socket, head) !->
console.log "upgrade dedected"
ws-proxy.ws(req, socket, head)
#console.log req, socket, head
console.log 'Proxy started @ ' + server.info.uri
Auto generated Javascript code is: 自动生成的Javascript代码为:
// Generated by LiveScript 1.3.1
(function(){
var hapi, httpProxy, server, wsProxy;
hapi = require("hapi");
httpProxy = require('http-proxy');
server = hapi.createServer(5000);
server.route({
method: '*',
path: '/my/app/{f*}',
handler: {
proxy: {
mapUri: function(request, callback){
var resourceUri, url;
resourceUri = request.url.path.replace('/my/app/', '/');
url = 'http://localhost:4000' + resourceUri;
console.log('url: ', url);
return callback(null, url);
},
passThrough: true,
xforward: true
}
}
});
wsProxy = httpProxy.createProxyServer({
target: 'http://localhost:4000/socket.io/'
});
wsProxy.on('error', function(err, req, res){
console.log("error caught: ", err);
});
server.start(function(){
server.listener.on('upgrade', function(req, socket, head){
console.log("upgrade dedected");
wsProxy.ws(req, socket, head);
});
console.log('Proxy started @ ' + server.info.uri);
});
}).call(this);
Is there any way to achieve same goal without hardcoding the websocket address of http://localhost:4000/socket.io/
? 有什么方法可以实现相同的目标,而无需对
http://localhost:4000/socket.io/
的websocket地址进行硬编码?
So from reading the code you always proxy to http://localhost:4000/socket.io/
, however you want this to be dynamic? 因此,通过阅读代码,您始终可以代理到
http://localhost:4000/socket.io/
,但是您希望它是动态的?
You could pass the server you wish to proxy to in the initial request as a parameter? 您可以在初始请求中将您希望代理的服务器作为参数传递给您? You could potentially pass this in the
protocol
field of the WebSocket constructor. 您可以在WebSocket构造函数的
protocol
字段中传递它。 Then read this on the servers on-open
event. 然后在服务器
on-open
事件on-open
阅读此内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.