'How to create a middle layer for two different servers running independently in node.js
I am trying to implement a node.js layer between two servers which will help in redirecting to the respective server on a route/url change, provided both the servers are inside one folder.
What I wanted to achieve:
If I hit localhost:8000/app1 --> server1 should be called
similarly, localhost:8000/app2 --> server2 should be called
So far I have tried:
const path = require("path");
const express = require("express");
const router = express.Router();
const PORT = 8000;
const server1 = require('./server1')
const server2 = require('./server2')
app.get('/app1', function(req, res){
res.send(server1);
});
app.get('/app2', function(req, res){
res.send(server2);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
I have also tried to understand express vhost in this scenario but did not got any success.
I would love to understand if this is possible?
Solution 1:[1]
Maybe Express provides this kind of functionality, but more likely you have to launch a web server like NGINX or Apache2. In their configuration you can tell that "http://localhost:8000/app1" has to be mapped to server1 and "http://localhost:8000/app2" has to be mapped to server 2. NGINX example:
Assume that server 1 is running on port 3001, and server2 on 3002.
location /app1 {
proxy_pass http://localhost:3001;
}
location /app2 {
proxy_pass http://localhost:3002;
}
Here's the guide: https://www.nginx.com/blog/deploying-nginx-plus-as-an-api-gateway-part-1/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |