NodeJS 如何在同一端口运行不同的服务器?

svmlkihl  于 2023-01-08  发布在  Node.js
关注(0)|答案(2)|浏览(402)

我已经用express和node.js创建了2个服务器,现在我想在同一个端口localhost:8000上用不同的端点运行这两个服务器。如何做到这一点?
附加服务器代码以供参考:-

服务器1:-

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}`);
});

服务器2:-

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}`);
});

当前运行时,一台服务器运行,另一台服务器显示端口8000已在使用中的错误。

z0qdvdin

z0qdvdin1#

你不能在同一个端口上运行两个服务器。操作系统和TCP协议栈不允许。
最简单的解决方案是在一台服务器上使用两个终结点。
如果您必须有两个独立的服务器,那么您可以在独立的端口上运行它们(这两个端口都不是公共端口),然后使用类似nginx的东西将每个独立的路径代理到适当的服务器。
因此,用户的请求将发送到代理,代理将检查请求的路径,然后根据请求的路径(如代理配置中的设置)将其转发到两个服务器中的一个。

aurhwmvo

aurhwmvo2#

不可能在同一端口上运行不同的服务器

相关问题