Home > Net >  How to run different server on same port?
How to run different server on same port?

Time:01-06

I have created 2 server with express and node.js and now I want to run both the server on the same port which is localhost:8000 with different end points. How it can be done or what can be the approach for it?

Attaching the server code for reference:-

Server1:-

const express = require("express");
const cors = require("cors");
const app = express();
const axios = require('axios');

app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
const PORT = 8000;

app.get("/WeatherForcast", function (req, res) {
  axios.get('https://localhost:7173/WeatherForecast')
  .then(response => {
    res.status(200).json({ success: true, data: response.data});
  })
  .catch(error => {
    console.log(error);
  });
});

app.listen(PORT, function () {
  console.log(`Server is running on ${PORT}`);
});

Server2:-

const express = require("express");
const cors = require("cors");
const app = express();
const axios = require('axios');

app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
const PORT = 8000;

app.get("/UserData", function (req, res) {
  axios.get('https://localhost:7173/UserData')
  .then(response => {
    res.status(200).json({ success: true, data: response.data});
  })
  .catch(error => {
    console.log(error);
  });
});

app.listen(PORT, function () {
  console.log(`Server is running on ${PORT}`);
});

Currently when I run it, one server runs and for other server an error is displayed that port 8000 is already in use.

CodePudding user response:

You can't run two servers on the same port. The OS and TCP stack won't allow it.

The easiest solution is to use two endpoints on one server.

If you have to have two separate servers, then you would run them both on separate ports (neither of which is the public port) and then use something like nginx to proxy each separate path to the appropriate server.

So, the user's request goes to the proxy and the proxy examines the path of the request and then forwards it to one of your two servers based on the path of the request (as setup in the proxy configuration).

CodePudding user response:

it is not possible to run different servers on same port

  • Related