Node http-proxy-middleware not working with local servers as targert

Yaniv Efraim picture Yaniv Efraim · Apr 20, 2016 · Viewed 9.8k times · Source

I have a node server and I am proxying my api requests using http-proxy-middleware, similar to what happens in this post. When I proxy to real production server everything works just fine, but when I point the proxy to a local server it just doesn't work.

This is my code:

app.use('/_api', proxy({target: 'http://localhost:9000', changeOrigin: true}));

The server on:

http://localhost:9000/hello is working (I can access it from my browser), but, when I try to access it from my own server, like this:

http://localhost:3000/_api/hello

I am getting:

Cannot GET /_api/hello

If I replace localhost:9000 with real server, everything works...

Answer

duncanhall picture duncanhall · Apr 20, 2016

Your proxied request is trying to access the local server using the original request path.

Eg, when you request

http://localhost:3000/_api/hello

Your proxy is trying to access

http://localhost:9000/_api/hello

The _api/hello path does not exist on your localhost:9000, which is shown by the Cannot GET /_api/hello error.

You need to rewrite your proxied request paths to remove the _api part:

app.use('/_api', proxy({
    target: 'http://localhost:9000', 
    changeOrigin: true,
    pathRewrite: {
        '^/_api' : '/'
    }
}));