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.

2
  • What is the result of example.com/api/v2/list?first=50 ? Commented Apr 23, 2022 at 9: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. Commented Apr 23, 2022 at 10:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I am using "http-proxy-middleware" on client side, but I need to pass path param to target how can I do that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.