Hi,
I need to proxy requests from /api to the root of other site: http://test.com:
/api/users -> http://test.com/users
/api/users/1 -> http://test.com/users/1
But all my requests lead to http://test.com/api/*
How to ignore /api prefix but not to ignore other path?
When I use ignorePath settings all my requests lead to http://test.com.
Config:
server.middleware = proxyMiddleware('/api', {target: 'http://test.com', proxyHost: 'test.com'});
Did you try the wildcard/globbing configuration?
https://www.npmjs.com/package/http-proxy-middleware#context-matching
It should give you the full control on which paths should be proxied or not.
server.middleware = proxyMiddleware('/api/**', {target: 'http://test.com', changeOrigin: true});
Wildcards/globbing is introduced in v0.3.0
Paths can be igored too:
proxyMiddleware(['/api/**', '!**/bad.json'], {target: 'http://test.com'}); //exclusion
@chimurai with this configuration
server.middleware = proxyMiddleware('/api/**', {target: 'http://test.com', changeOrigin: true});
when I call $http.get('/api/users') request is proxied to http://test.com/api/users, but I need http://test.com/users (without prefix /api in the target URL)
Ah, didn't read your question well... :)
You can rewrite paths with the pathRewrite option.
https://www.npmjs.com/package/http-proxy-middleware#options
var options = {
target: 'http://test.com',
changeOrigin: true,
pathRewrite: {'^/api' : ''} // <-- this will remove the /api prefix
};
server.middleware = proxyMiddleware('/api', options);
This is exactly what I was looking for! Thank you, man.
Not all that "impossible" :)
Thanks for the question. This might be useful for users running into the same problem.
@chimurai
Need to improve documentation and more example.
var httpProxyMiddleware = require('http-proxy-middleware');
var abcProxy = httpProxyMiddleware({
target: 'http://localhost:8443',
changeOrigin: false, // for vhosted sites, changes host header to match to target's host
pathRewrite: {
"^/abc" : "" // rewrite path
},
logLevel: 'debug'
});
// Add the proxy to express
//app.use(abcProxy);
app.use('/abc', abcProxy);
I have to put forward slash, and this work: http://localhost:3000/abc/
But without forward slash, it does not work. http://localhost:3000/abc
Can we add a boolean option to plainly avoid path prefixing. pathRewrite still sound complex.
Most helpful comment
Ah, didn't read your question well... :)
You can rewrite paths with the
pathRewriteoption.https://www.npmjs.com/package/http-proxy-middleware#options