expressnode-http-proxyhttp-proxy-middleware

http-proxy-middleware adds a '/' before query parameters


I want to consume an API using a proxy written in express. I use http-proxy-middleware for this. Here is the setup I have:

app.use(
  createProxyMiddleware('/api', {
    target: 'http://example.com/api/v2',
    changeOrigin: true,
    pathRewrite: {
      '/api': '',
    }
  })
);

Then I make a request from postman or browser: GET http://localhost:8080/api/list?first=50

All I get from the API server is 404. I saw in the browser that the URL changes to http://localhost:8080/api/v2/list/?first=50 and I don't understand why.

All I want is to add an auth header which I managed to do using onProxyReq, but now I just want everything that comes after /api to be forwarded as is to http://example.com/api/v2.


Solution

  • I just got it to work. Turns out I had some things wrong. The first wrong thing target: 'http://example.com/api/v2' should be target: 'http://example.com'. Then, pathRewrite will rewrite anything it matches and redirect to the new path, so it ended up calling localhost:8080/api/list?first=50 and then localhost:8080/api/v2/list/?first=50. So with these 2 mistakes combined, in the end the API call would be example.com/api/v2/v2/list/?first=50 and that's clearly wrong. I replaced the target and I am now using /api/v2 as context for the proxy.

    I would still like to call my proxy using localhost:8080/api/whatever and have it turned into example.com/api/v2/whatever, but it's just a nice to have.