krishnanspace
krishnanspace

Reputation: 423

Proxy all requests to server in React using createProxyMiddleware

So on my dev env, I have a React Server on localhost:3000 and a NodeJs server on localhost:5000.

I have used createProxyMiddleware in React to configure the requests. Here is my config:

const {createProxyMiddleware} = require('http-proxy-middleware');
    module.exports = function (app) {
      app.use(createProxyMiddleware('/auth/google', {target: 'http://localhost:5000'}));
      app.use(createProxyMiddleware('/auth/currentUser', {target: 'http://localhost:5000'}));
      app.use(createProxyMiddleware('/api/*', {target: 'http://localhost:5000'}));
}

All of these routes work without any problems. For example I have a route like localhost:3000/api/list which gets routed to localhost:5000/api/list.

But now I have a route like localhost:3000/api/list/3132133ffdvf. The random string is some id. This above route does not get proxied. It gives me a 404.

Why is this happening? It shouldn't happen since I have created a proxy for /api/*. Can someone help me out?

Upvotes: 1

Views: 8162

Answers (1)

cbr
cbr

Reputation: 13642

The wildcard (*) only matches one directory level. This means that it matches /api/list but not /api/list/id, since the latter has two levels.

Either remove the wildcard, or use a globstar (**):

app.use(createProxyMiddleware('/api', {target: 'http://localhost:5000'}));

or

app.use(createProxyMiddleware('/api/**', {target: 'http://localhost:5000'}));

Upvotes: 2

Related Questions