It is very common for developer to have react app supported by nodejs API for backend. In some cases developer may use API developed in php or any other programming knowledge.
When it comes to deployment, programmer may face difficulty in deploying both on same server. As one can only host single application to single port.
Hosting multiple application on same server can face below problems:
- One or the other app might use port in public URL.
- Might require backend to be mapped to different domain or sub domain which can introduce cross site script or call challenge.
To come over mentioned drawbacks, one can use proxy. Proxy can help user to redirect request to different port but still not require to rewrite URL.
In below video, http-proxy package is used to handle the request:
const fs = require("fs");
var https = require("https"),
httpProxy = require("http-proxy");
var proxy_web = new httpProxy.createServer({
target: "http://localhost:8080/",
secure: true,
});
var proxy_api = new httpProxy.createServer({
target: "http://localhost:8081/",
secure: true,
});
https
.createServer(
{
key: fs.readFileSync("server.key"),
cert: fs.readFileSync("server.cert"),
ca: fs.readFileSync("serverCA.pem"),
},
function (req, res) {
try {
if (req.headers.host === "**DOMAIN.COM**") {
if(!req.url.includes("/api"))
{
proxy_web.proxyRequest(req, res);
proxy_web.on("response", (remoteRes) => {
res.writeHead(remoteRes.statusCode, remoteRes.headers);
remoteRes.pipe(res);
});
proxy_web.on("error", function (err, req, res) {
if (err) console.log(err);
res.writeHead(500);
res.end("Oops, something went very wrong...");
});
}
else{
req.url = req.url.replace('/api', '/')
proxy_api.proxyRequest(req, res);
proxy_api.on("response", (remoteRes) => {
res.writeHead(remoteRes.statusCode, remoteRes.headers);
remoteRes.pipe(res);
});
proxy_api.on("error", function (err, req, res) {
if (err) console.log(err);
res.writeHead(500);
res.end("Oops, something went very wrong...");
});
}
} else if (req.headers.host === ""**SUBDOMAIN.DOMAIN.COM**") {
proxy_api.proxyRequest(req, res);
proxy_api.on("response", (remoteRes) => {
res.writeHead(remoteRes.statusCode, remoteRes.headers);
remoteRes.pipe(res);
});
proxy_api.on("error", function (err, req, res) {
if (err) console.log(err);
res.writeHead(500);
res.end("Oops, something went very wrong...");
});
}
} catch (error) {
console.log(error)
}
}
)
.listen(443, function () {
console.log("App is running on the port", 443);
});