Michael
Michael

Reputation: 903

How to proxy to root path with node http-proxy

I am trying to setup a proxy with an express app to a root path from a specific path in my application:

http://my-domain.com/some/route --> http://another-domain:8000/

I have tried multiple things per the http-proxy docs but I keep hitting a wall with the paths/routing. I am trying to do this within a logged in express app so that I can utilize my authentication behind the app i'm trying to proxy too. I keep getting an error with the proxy'd app saying the path '/some/route' is not defined...etc.

var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});

proxy.proxyRequest(req, res, {
    host:'localhost',
    port:8000
});

I've also tried:

var url = 'http://localhost:8000/';
var httpProxy = require('http-proxy'),
    proxy = httpProxy.createProxyServer({});

proxy.web(req,res, { target: url }, function(e) {
    console.log('proxy.web callback');
    console.log(e);
});

The function calls but I end up with an express 404 error...

I would also like to pass in some variables if that is possible so for example:

http://my-domain.com/some/route?var1=something&var2=something --> http://another-domain:8000/?var1=something&var2=something

But could not figure out if that was possible, I tried setting it on the request since that was being sent into the proxyRequest, but was unable to find them in the second application.

Upvotes: 8

Views: 12260

Answers (2)

mik01aj
mik01aj

Reputation: 12382

No, you can't do this with just node-http-proxy.

But it's possible with http-proxy-middleware (and you likely use it already):

From comment by @chimurai on github:

You can rewrite paths with the pathRewrite option.

var options = {
  target: 'http://test.com',
  changeOrigin: true,
  pathRewrite: {'^/api' : ''}      // <-- this will remove the /api prefix
};

server.middleware = proxyMiddleware('/api', options);

And if you come here because you're using webpack-dev-server, note that it also internally uses http-proxy-middleware, starting from version 2.0.0-beta (see PR).

Side note: There is also a node-proxy plugin, http-proxy-rules, so you can use this one if you don't want middleware.

Upvotes: 11

Wilm
Wilm

Reputation: 41

Well, I encounter another problem, but needed to solve this problem first. I came up with this code, which worked fine for me ;)

Just use this for "/some/route"

.... // your stuff

httpProxy.on('error', function (err, req, res) {
    res.writeHead(500, {
        'Content-Type': 'text/plain'
    });
    res.end('some error');
});

app.all( '/some/route/*' , function( req , res ) {

        var url = req.url;
        url = url.slice(11); // to remove "/some/route"

        req.url = url;

        return httpProxy.web(req, res , { target: "http://another-domain:8000" } );

} );

hope this helps.

Upvotes: 2

Related Questions