【问题标题】:Run multiple Node.js apps on the same server在同一台服务器上运行多个 Node.js 应用程序
【发布时间】:2021-03-02 18:28:37
【问题描述】:

我想在同一台服务器上运行多个 Node js 应用程序,到目前为止,我在此处针对类似问题做了一些进度检查解决方案(链接如下)。假设我有 2 个应用程序,每个应用程序都提供一些 html 文件,我想通过访问来访问每个应用程序 https://example.com/app1https://example.com/app2
到目前为止,我有我的主应用程序,我的方法是调用此应用程序,然后它将客户端重定向到这两个应用程序之一。
我的主应用如下所示:

const express = require('express');
const app = express();

app
  .use('/app1', require('./app1/index.js'))
  .use('/app2', require('./app2/index.js'))
  .listen(80);

我的两个子应用(app1 和 app2)中的每一个看起来都像这样

const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./routes/api');
const mongoose = require('mongoose');
require('dotenv/config');

const app = express();

mongoose.connect(
    process.env.DB_CONNECTION,
    { useNewUrlParser: true, useUnifiedTopology: true }, () =>
    console.log('Connected to DB')
);
mongoose.Promise = global.Promise;

app.use(express.static('public'));
app.use(bodyParser.json());

app.use('/', routes); 

app.use(function (err, req, res, next) {
    res.status(422).send({ error: err.message })
});

问题是我在部署这些应用程序并访问后什么都没有得到。 https://example.com/app1
我对这一切都很陌生,所以这里可能是初学者的错误。有人可以帮忙吗?

相关问题How to mount express.js sub-apps?Running multiple Node (Express) apps on same port

【问题讨论】:

  • 您应该查看 express.Router 并从它们单独的文件中导出应用程序,因为如果没有导出,只需一个文件不会返回任何内容
  • 使用像nginx这样的反向代理,你不需要手动处理。在两个不同的 prot 上运行这两个应用程序。它可以匹配 url 中的模式,根据该模式将请求重定向到相应的应用程序。
  • 我想如果您将module.exports = app 添加到您的应用文件中,这应该可以正常工作

标签: javascript node.js express


【解决方案1】:

如果你想在 node 中运行完全不同的应用程序,你可以使用 apache/nginx 的 proxy_pass/reverse proxy。 为此,您的每个应用程序都应该在它们自己的端口和一些其他服务器(apache/nginx/etc)上运行,将请求传递给它们中的每一个

我使用这种技术托管了几个节点应用程序,它们工作得非常好(nginx 比 apache 快得多)。此外,您可能会考虑直接阻止从 Internet 访问节点应用程序端口。

【讨论】:

  • 我最终决定使用 nginx,到目前为止,当我访问 www.mydomain.com:3000 和 www.mydomain.com:4000 时,我可以看到我的两个应用程序正在运行,但是,我'我想通过例如打开它们www.mydomain.com/app1。我已将 /etc/nginx/sites-available/default 中的位置更改为:location /app1/ { proxy_pass http://myIPaddress:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } 但加载时出现“无法获取 /app1/”
  • 好吧,想通了——我只需要在我的反向代理中多写几行代码,以此为例flaviocopes.com/nginx-reverse-proxy
  • 很高兴你做到了,之前回答你的评论有点超出了stackoverflow的要求
猜你喜欢
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 2019-10-29
  • 1970-01-01
  • 2021-02-10
  • 2016-05-11
  • 1970-01-01
相关资源
最近更新 更多