11

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...

Community
  • 1
  • 1
Yaniv Efraim
  • 6,633
  • 7
  • 53
  • 96

1 Answers1

25

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' : '/'
    }
}));
duncanhall
  • 11,035
  • 5
  • 54
  • 86
  • wouldn't the prependPath parameter will do this? – celerno Feb 13 '20 at 04:24
  • @duncanhall can you help me on this , im trying to proxying my request from local to qa or prd , its not even recognizing the path which ever i have given , (https://stackoverflow.com/questions/64639757/http-proxy-middleware-the-path-is-not-recognising) – SakthiSureshAnand Nov 02 '20 at 08:49