chimurai / http-proxy-middleware

:zap: The one-liner node.js http-proxy middleware for connect, express, next.js and more
MIT License
10.76k stars 850 forks source link

How to modify query parameters #184

Closed victorbucutea closed 7 years ago

victorbucutea commented 7 years ago

I seem to have a simple problem, but with a long time to solve ...

What am I doing wrong as I can't find neither a document nor an example about this query parameter.

router.use('/some_url', proxy({
      logLevel: 'debug',
      target: serviceInstance.uri,
      pathRewrite: {
        '^/px-api/intelligent-mapping/tulip/': '/v1/collections/'
      },
      changeOrigin: true,
      onProxyReq: function (proxyReq, req, res) {
        // add custom header to request
        proxyReq.setHeader('Predix-Zone-Id', serviceInstance.zoneId);
        proxyReq.setHeader('X-Subtenant-Id', serviceInstance.zoneId);
        /// ?? how can I rewrite the params here ???
      }
    }
  ));
chimurai commented 7 years ago

Think the custom pathRewrite is what you are looking for.

Provide a custom function and you can implement your own rewrite logic; Including rewriting query params.

Docs: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md#custom-rewrite-function

klis87 commented 6 years ago

@victorbucutea You could also do:

    onProxyReq: (proxyReq, req, res) => {
      proxyReq.path += '?key=value';
    },
christiaanwesterbeek commented 4 years ago

In my case I needed to remove a query parameter from the path. Just for reference, I'll leave my implementation for this.

const querystring = require('querystring');

// ...

pathRewrite: (path, req) => {
    let newPath = path.replace(/^\/api/, '/base/api');

    // Strip query parameter _csrf
    if (req.method === 'GET' && /_csrf=/.test(newPath)) {
        const newQuery = { ...req.query }; // copy object
        delete newQuery._csrf;

        if (Object.keys(newQuery).length) {
            // There were more query parameters than just _csrf
            newPath = `${newPath.split('?')[0]}?${querystring.stringify(newQuery)}`;
        } else {
            // _csrf was the only query parameter
            newPath = `${newPath.split('?')[0]}`;
        }
    }

    return newPath;
},
grubersjoe commented 1 year ago

Here's a more flexible approach using URL to parse and modify the query:

onProxyReq: (proxyReq, req, res) => {
    const baseUrl = `${proxyReq.protocol}//${proxyReq.host}`;
    const url = new URL(proxyReq.path, baseUrl);
    url.searchParams.append('key', process.env.API_KEY);
    proxyReq.path = url.pathname + url.search;
}