'How to rewrite request path using http-proxy-middleware in a react app?

I am using http-proxy-middleware in my react app, where I have a setup like this:

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

module.exports = function(app) {
  app.use(
    "/api/v1",
    createProxyMiddleware({
      target: "https:test.com/",
      changeOrigin: true
    })
  );
};

Some api requests of my applications has request url as: http://localhost:3000/products-and-details/api/v1/proxy/trend/api/v1/listProducts which I want to change it to: http://localhost:3000/api/v1/proxy/trend/api/v1/listProducts.

To achieve this I am modifying request paths before requests are send to the target using pathRewrite as below:

pathRewrite: {
        '^/products-and-details': ''
      }

However this doesn't seem to work and the request url remains the same with no changes. Can anyone please help to point out what am I doing wrong here?

Edit: My http-proxy-middleware dependency has a version ^2.0.3



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source