-1

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.

Avanish
  • 51
  • 6
  • 2
    Does this answer your question? [Can two applications listen to the same port?](https://stackoverflow.com/questions/1694144/can-two-applications-listen-to-the-same-port) – gre_gor Jan 06 '23 at 08:33

3 Answers3

1

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).

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

it is not possible to run different servers on same port

0

Two different servers can not be hosted on same port as it will give the error i.e "this port is currently is use" something like this.

The thing that can be done is instead of creating multiple server you can create a single server and define different endpoints to manage the code flow.