I'm using http-proxy
to create a simple proxy: localhost:3000?q=${encodeURIComponent(targetURL)}
will access targetURL
using the proxy.
Here's my working code:
var http = require("http");
var httpProxy = require("http-proxy");
//create a server object:
http
.createServer(function (req, res) {
try {
// Get the `?q=` query param.
const url = req.query.q;
const parsed = new URL(decodeURIComponents(url));
const proxy = httpProxy.createProxyServer();
// Fix URLs and query params forwarding.
// https://stackoverflow.com/questions/55285448/node-http-proxy-how-to-pass-new-query-parameters-to-initial-request
proxy.on("proxyReq", function (proxyReq) {
proxyReq.path = parsed.toString();
});
proxy.on("end", () => res.end());
// Avoid the following error:
// "Error [ERR_TLS_CERT_ALTNAME_INVALID]: Hostname/IP does not match certificate's altnames"
req.headers["host"] = parsed.host || undefined;
proxy.web(req, res, { target: url }, (err) => {
throw err;
});
} catch (err) {
res.write(JSON.stringify({ error: err.message }));
res.end();
}
})
.listen(8080); //the server object listens on port 8080
When I visit localhost:3000?q=https://google.com
, everything works. However, if I click on a link in the website, then the route is changed on my hostname directly, not in the query param.
So:
- I go to
localhost:3000?q=https://google.com
- I click on "Images', which should bring me to
localhost:3000?q=https://google.com/images
- instead, it brings me to
localhost:3000/images?q=https://google.com
, which 404s
How do I solve navigation in the target website?