Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http-proxy-middleware does not forward the full path

I am trying to configure BrowserSync to work in server mode and to proxy my API requests to the backend that runs on the same machine on a different port, using http-proxy-middleware. I use Gulp to launch BrowserSync.

BrowserSync runs on port 8081. My backend runs on 8080.

Here is how I create the proxy middleware :

var proxyApi = proxy('/api', {target : 'http://localhost:8080/api', logLevel : 'debug'});

And here is how I run BrowserSync from my Gulp task :

// Init BrowserSync with proxies as middleware and based on the dest dir
browserSync.init({
    open: true,
    port: config.proxyPort,
    server: {
        baseDir: config.destDir,
        middleware: [proxyApi]
    },
    browser: "google chrome"
});

The output :

[HPM] Proxy created: /api  ->  http://localhost:8080/api

Everything looks good.

But When I hit e.g. http://localhost:8081/api/users, the output is :

[HPM] GET /api/users/123 -> http://localhost:8080/api

...And my client gets a 404 error because /api on its own does not match anything on the backend.

From what I understood from the doc and examples, the target should actually be http://localhost:8080/api/users/123

Why is the rest of the path (in this case /users/123) being left out ?

Using the following versions :

"gulp": "3.9.1",
"browser-sync": "2.16.0",
"http-proxy-middleware": "0.17.1",
like image 889
Pierre Henry Avatar asked Mar 12 '23 02:03

Pierre Henry


1 Answers

The prependPath option is true by default. This option is provided by the underlying lib: http-proxy.

prependPath: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path

There are two ways to fix the issue:

1.) Change your target from 'http://localhost:8080/api' to 'http://localhost:8080'

var proxyApi = proxy('/api', {target: 'http://localhost:8080', logLevel: 'debug'});

2.) Alternatively you can set the option prependPath to false.

var proxyApi = proxy('/api', {target: 'http://localhost:8080/api', prependPath: false, logLevel: 'debug'});
like image 113
chimurai Avatar answered Mar 23 '23 19:03

chimurai