Search code examples
node.jsexpressnode-http-proxy

Error when using node-http-proxy with expressjs


I do not get the last version of node-http-proxy working (this used to work in a previous version though). Node.js version is 0.6.12, node-http-proxy version is 0.8.0. Basically, I have a server listening on port 10000 and another one listening on port 5000. I 'd like to proxy to this last guy all the requests starting with /api (after having removed this prefix).

My code is:

var express = require("express");
var httpProxy = require('http-proxy');
var cluster = require('cluster');
var fs = require('fs');

// Use http server for local tests
var app = express.createServer();

// Proxy request targeting API
app.all('/api/*',function(req, res){

  // Remove '/api' part from query string
  req.url = '/' + req.url.split('/').slice(2).join('/');

  // Create proxy
  var proxy = new httpProxy.HttpProxy();
  proxy.proxyRequest(req, res, {
    target: {
      host: 'localhost',
      port: 5000
    }
  });
});

// Handle static files
app.use(express.static(__dirname + '/public'));

// Run application
app.listen(10000);

The static files are correctly served but when it comes to the proxy stuff, I got this error:

Error: Both `options` and `options.target` are required.
at new <anonymous> (/Users/luc/Projects/test/www/node_modules/http-proxy/lib/node-http-proxy/http-proxy.js:53:11)
at /Users/luc/Projects/test/www/server.js:15:16
at callbacks (/Users/luc/Projects/test/www/node_modules/express/lib/router/index.js:272:11)
at param (/Users/luc/Projects/test/www/node_modules/express/lib/router/index.js:246:11)
at pass (/Users/luc/Projects/test/www/node_modules/express/lib/router/index.js:253:5)
at Router._dispatch (/Users/luc/Projects/test/www/node_modules/express/lib/router/index.js:280:4)
at Object.handle (/Users/luc/Projects/test/www/node_modules/express/lib/router/index.js:45:10)
at next (/Users/luc/Projects/test/www/node_modules/express/node_modules/connect/lib/http.js:203:15)
at Object.handle (/Users/luc/Projects/test/www/node_modules/express/lib/http.js:83:5)
at next (/Users/luc/Projects/test/www/node_modules/express/node_modules/connect/lib/http.js:203:15)-error-undefined

I've added the target as requested but still the same error.


Solution

  • You need to pass your options to the HttpProxy constructor function, not to the proxyRequest function.

    https://github.com/nodejitsu/node-http-proxy/blob/master/lib/node-http-proxy/http-proxy.js#L51