2

I have a react app started with CRA, and a backend server set up for my react app.

My fetch requests go something like

const res = await fetch("/applications", {
...

I have set it up my app with a proxy middleware using http-proxy-middleware

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    createProxyMiddleware({
      target: 'https://projects.mydomain.com/', 
      changeOrigin: true,
    })
  );
};

When I make a request to the backend using fetch("/applications") my request get's parsed as fetch("/projects.mydomain.com/applications")

However I need to add a url path to the begining of all my fetch requests, my final desired result is:

fetch("/projects.mydomain.com/b2b-iys/applications")

I tried doing this:

  app.use(
    '/b2b-iys/',
    createProxyMiddleware("/b2b-iys", {
      target: 'https://projects.muhammed-aldulaimi.com/', 
      changeOrigin: true,
    })
  );

But that didn't work.

I would ideally like to add it to my proxy rather than change the files one by one.

What's the solution here?

momomo
  • 319
  • 1
  • 5
  • 15

1 Answers1

0

From the http-proxy-middleware documentation I think you can use the pathRewrite option to add a base path :

app.use(
  createProxyMiddleware({
    target: 'https://projects.mydomain.com', 
    changeOrigin: true,
    pathRewrite: {'^/': '/b2b-iys/'}
  })
);
Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56
  • When I did that, after starting the application I got redirected to my home page (https://projects.mydomain.com) instead of react local development build. – momomo Sep 20 '21 at 18:28
  • I also noticed that this behaviour is a result of using http-proxy-middleware library, when I use the default proxy option in my package.json provided by CRA, when a connection fails to establish it still displays my application on my original react port (300) – momomo Sep 20 '21 at 18:36