express-http-proxy
express-http-proxy copied to clipboard
Sub path is not working...
I have a simple question.
Is this library support sub path?
I want to access json data using url like below
https://public-api.wordpress.com/rest/v1.1/sites/uxengineer.wordpress.com/posts
app.use(
'/api',
proxy('https://public-api.wordpress.com/rest/v1.1/sites/uxengineer.wordpress.com', {
proxyReqOptDecorator(opts) {
opts.headers['x-forwarded-host'] = 'localhost:3000';
return opts;
}
})
);
I tried to access http://localhost:3000/api/posts
but It is not working
{ "error": "not_found", "message": "The specified path was not found. Please visit https://developer.wordpress.com/docs/ for valid paths." }
I changed like below and It works fine
app.use(
'/api',
proxy('https://public-api.wordpress.com', {
proxyReqOptDecorator(opts) {
opts.headers['x-forwarded-host'] = 'localhost:3000';
return opts;
}
})
);
This is working fine...
http://localhost:3000/api/rest/v1.1/sites/uxengineer.wordpress.com/posts
The result is
{"ID":152056136,"name":"ShawnBaek","description":"","URL":"https:\/\/uxengineer.wordpress.com","jetpack":false,"subscribers_count":1,"lang":false,"logo":{"id":0,"sizes":[],"url":""},"visible":null,"is_private":false,"is_following":false,"meta":{"links":{"self":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/152056136","help":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/152056136\/help","posts":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/152056136\/posts\/","comments":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/152056136\/comments\/","xmlrpc":"https:\/\/uxengineer.wordpress.com\/xmlrpc.php"}}}
My question is
Why proxy url with sub path is not work ?
How to solve this problem?
Can confirm this is also an issue for me.
I experienced this issue, too, but I think this may be a misunderstanding with how express-http-proxy
works. The idea is that you can forward a given path to a given host. Any subpath after that specified path will be added to the host request. For example, doing app.use('/foo', 'http://google.com'
will proxy requests to just http://google.com
when the user goes to the route /foo
. However, when the user goes to /foo/bar
, it'll proxy http://google.com/bar
.
To get around this (if you want an entire path to be forwarded instead), do something like the following:
app.use('/foo', proxy('google.com', {
proxyReqPathResolver: function(req) {
return '/foo';
}
});
Note that this means /foo/bar
will go to google.com/foo
.
@ShawnBaek you can use proxyReqPathResolver to include the fixed path, so when you send a request to http://localhost:3000/api/post
, it will become host + fixed path + your request url (which does not include the /api)
app.use(
'/api',
proxy('https://public-api.wordpress.com', {
proxyReqPathResolver: function(req) {
return '/rest/v1.1/sites/uxengineer.wordpress.com' + req.url;
}
})
);