2016-03-05 33 views
0

我下面http://blog.nodejitsu.com/http-proxy-intro/寫我的代理服務器來指向子域當我使用節點運行此文件到節點不同的端口子域使用HTTP代理不顯示節點上運行的應用程序

var http = require('http'), 
httpProxy = require('http-proxy'); 

// 
// Just set up your options... 
// 
var options = { 
    hostnameOnly: true, 
    router: { 
    'localhost': '127.0.0.1:80' 
    'sub.localhost': '127.0.0.1:9012', 
    } 
} 

// 
// ...and then pass them in when you create your proxy. 
// 
var proxyServer = httpProxy.createServer(options).listen(80) 

上運行的應用程序和嘗試訪問localhostsub.localhost,我收到此錯誤。我真的不明白什麼是錯的。

Error: Must provide a proper URL as target 
    at ProxyServer.<anonymous> (D:\myProjects\bitbucket\temp\node_modules\http-proxy\lib\http-proxy\index.js:68:35) 
    at Server.closure (D:\myProjects\bitbucket\temp\node_modules\http-proxy\lib\http-proxy\index.js:125:43) 
    at emitTwo (events.js:87:13) 
    at Server.emit (events.js:172:7) 
    at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:525:12) 
    at HTTPParser.parserOnHeadersComplete (_http_common.js:88:23) 
+0

看到http://stackoverflow.com/a/24108494無關的問題,但它有你需要的答案。 – Neilos

回答

1

試試這個:

var http = require("http"); 
var httpProxy = require("http-proxy"); 

// reverse proxy 
var proxy = httpProxy.createProxyServer(); 
http.createServer(function (req, res) { 
    var target, 
     domain = req.headers.host, 
     host = domain.split(":")[0]; 
    ////////////////// change this as per your local setup 
    ////////////////// (or create your own more fancy version! you can use regex, wildcards, whatever...) 
    if (host === "localhost") target = {host: "localhost", port: "2000"}; 
    if (host === "testone.localhost") target = {host: "localhost", port: "3000"}; 
    if (host === "api.testone.localhost") target = {host: "localhost", port: "4000"}; 
    ////////////////// 
    proxy.web(req, res, { 
     target: target 
    }); 
}).listen(8000); 
+0

非常感謝您的回答。你的答案確實解決了這個問題。如果您能回答問題的第二部分,我將不勝感激,因爲錯誤意味着錯誤意味着「錯誤:必須提供一個適當的URL作爲目標」。 – NarayaN

+1

我不確切地知道這個錯誤是什麼意思,但是(猜測)我懷疑這是因爲你沒有在你的'options'對象中提供'target'字段; 「路由器」字段被忽略,因爲它已被刪除,所以您的代理永遠不知道發送請求的位置。 – Neilos

+1

本質上在我展示的例子中,我們正在編寫我們自己的路由器。這就是爲什麼我建議它可以改變/改進,它是真的由你來創建自己的路由器邏輯,你可以看到,一旦你知道如何連接它並不困難。你總是可以找到一個路由器插件來爲你做這件事,但無論如何我不會認爲上述代碼是一個足夠的生產就緒解決方案:它需要做的就是將字符串映射到對象並處理不匹配的情況,如果你有一個複雜的設置,通配符/正則表達式的支持也會使你受益。 – Neilos

相關問題