Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 640
Yaniv Efraim Avatar asked Apr 20 '16 13:04

Yaniv Efraim


1 Answers

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' : '/'
    }
}));
like image 187
duncanhall Avatar answered Sep 28 '22 05:09

duncanhall