proxy-module
proxy-module copied to clipboard
Add ability to use context matching function
What problem does this feature solve?
The following example is in the README for http-proxy-middleware, but AFAICT, cannot be implemented in proxy-module:
var filter = function(pathname, req) {
return pathname.match('^/api') && req.method === 'GET';
};
var apiProxy = proxy(filter, { target: 'http://www.example.org' });
I would like the ability to use context matching functions.
What does the proposed changes look like?
On a user level it might look like:
proxy: {
[(pathname, req) => pathname.match('^/api') && req.method === 'GET']: { target: 'http://www.example.org' }
},
I've just got this working for my own project by using this syntax:
proxy: [
[
(pathname, req) => pathname.match('^/api') && req.method === 'GET',
{ target: 'http://localhost:8000/' }
]
]
Basically, use the longhand syntax (the outer array instead of an object), and use a tuple of [selector, options] where selector can be a string or a function.
doesn't seem to work during SSR axios ignores these rules
I also think this would be a very nice feature since it would support dynamic contexts, i.e., context set at build time. For example, when running the app behind a reverse-proxy with a specific context path, the context path needs to be hard ooded and cannot be set e.g. via an env variable.
I'm not into this project but I guess it's kinda easy to implement by updating src/options.ts
line 4 and 24 so that it does not only use the key
as context but provide an own entry in the dict with the value either a function or string literal
I'm able to use custom matching and custom rewrite by doing the following: (you can omit the docker part of course)
const proxyConfig = () => {
// ------------------ proxy config for API ----------------------
let apiProxyTarget = ''
const ctxPath = process.env.APP_CTX_PTH || '/'
if (process.env.APP_DEPLOY === 'docker') {
const dockerApiHost = process.env.API_HOST
const dockerApiPort = process.env.API_PORT
apiProxyTarget = 'http://' + dockerApiHost + ':' + dockerApiPort + '/'
} else {
apiProxyTarget = 'http://localhost:8081/'
}
// https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md#custom-rewrite-function
const apiCustomRewrite = (pth, req) => {
const ctx = `${ctxPath}api/`
return pth.replace(ctx, '/')
}
// https://github.com/chimurai/http-proxy-middleware#context-matching
const apiCustomMatching = (pathname, req) => {
const ctx = `${ctxPath}api/`
return pathname.match(ctx)
}
return [
[
apiCustomMatching,
{
target: apiProxyTarget,
pathRewrite: apiCustomRewrite,
},
],
}
proxy: proxyConfig()