Search code examples
node.jshttpsubdomainhttp-proxy

subdomains using http-proxy does not display node running app


I am following http://blog.nodejitsu.com/http-proxy-intro/ to write up my proxy server to point sub domains to node apps running on different port

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)

When i run this file using node and try to access localhost or sub.localhost, I get this error back. I cant really understand whats going wrong.

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)

Solution

  • Try this:

    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);