0

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.

George D
  • 41
  • 1
  • 2
  • 9
  • What is the result of http://example.com/api/v2/list?first=50 ? – Heiko Theißen Apr 23 '22 at 09:57
  • @HeikoTheißen When called directly through postman the request succeeds and the result is a JSON. When called through the proxy the result is also a JSON, but the content is `{ "summary": "Not found.", "status_code": 404 }`. The result is the same as when calling [example.com/api/v2/non/existing/path](http://example.com/api/v2/non/existing/path). – George D Apr 23 '22 at 10:47

1 Answers1

0

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.

George D
  • 41
  • 1
  • 2
  • 9