[英]More elegant way of creating reverse proxy with Node.js
我正在使用hapi.js
在應用程序中提供html內容。 現在,我需要代理一些可能使用WebSocket的服務。
這是在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
自動生成的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);
有什么方法可以實現相同的目標,而無需對http://localhost:4000/socket.io/
的websocket地址進行硬編碼?
因此,通過閱讀代碼,您始終可以代理到http://localhost:4000/socket.io/
,但是您希望它是動態的?
您可以在初始請求中將您希望代理的服務器作為參數傳遞給您? 您可以在WebSocket構造函數的protocol
字段中傳遞它。 然后在服務器on-open
事件on-open
閱讀此內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.