You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将两款MEAN栈应用(分占3000/3001端口)迁移至3002端口同页运行?

Alright, let's figure out how to get your two MEAN stack apps (calendar and todo list) running together on port 3002, all accessible from the same webpage. I’ve got two solid approaches for your Ubuntu 16.04 setup—pick the one that fits how much you want to refactor your code:

方案1:整合到同一个Express服务器(最推荐的长期方案)

This approach merges both apps into a single codebase, which makes maintenance easier down the line. Here’s how to do it:

  • Set up a main Express project
    Either create a new empty Express app, or use one of your existing apps as the "main" project. If starting fresh, run:

    mkdir combined-mean-app && cd combined-mean-app
    npm init -y
    npm install express cors dotenv
    
  • Merge frontend code (Angular)

    1. Build both your calendar and todo apps using ng build (if using Angular CLI) to generate production-ready static files.
    2. Move the dist folders of both apps into the main project’s static directory (or combine them into a single dist folder with subdirectories like dist/calendar and dist/todo).
    3. Add a main navigation page (or use Angular routing) to switch between the two apps. For example, set up Angular routing in the main app:
      // app-routing.module.ts
      import { NgModule } from '@angular/core';
      import { RouterModule, Routes } from '@angular/router';
      import { CalendarComponent } from './calendar/calendar.component';
      import { TodoListComponent } from './todo/todo-list.component';
      
      const routes: Routes = [
        { path: 'calendar', component: CalendarComponent },
        { path: 'todo', component: TodoListComponent },
        { path: '', redirectTo: '/calendar', pathMatch: 'full' }
      ];
      
      @NgModule({
        imports: [RouterModule.forRoot(routes)],
        exports: [RouterModule]
      })
      export class AppRoutingModule { }
      
    4. Add navigation links in your main app.component.html:
      <nav>
        <a routerLink="/calendar">Calendar App</a>
        <a routerLink="/todo">Todo List</a>
      </nav>
      <router-outlet></router-outlet>
      
  • Merge backend APIs

    1. Copy the route files from both apps into the main project’s routes directory.
    2. Import these routes into your main server.js and prefix them to avoid conflicts:
      const express = require('express');
      const app = express();
      const calendarRoutes = require('./routes/calendar-routes');
      const todoRoutes = require('./routes/todo-routes');
      
      // Enable CORS and parse JSON
      app.use(cors());
      app.use(express.json());
      
      // Mount routes with unique prefixes
      app.use('/api/calendar', calendarRoutes);
      app.use('/api/todo', todoRoutes);
      
      // Serve static Angular files
      app.use(express.static('dist'));
      
      // Handle Angular HTML5 mode (prevents 404 on refresh)
      const fallback = require('express-history-api-fallback');
      const root = __dirname + '/dist';
      app.use(fallback('index.html', { root: root }));
      
      // Listen on port 3002
      app.listen(3002, () => {
        console.log('Combined MEAN app running on http://localhost:3002');
      });
      
  • Resolve dependency conflicts
    Check the package.json files of both original apps, and make sure all shared dependencies (like express, mongoose, @angular/core) use compatible versions in the main project. Run npm install to sync dependencies.

方案2:用Nginx反向代理(最小代码改动)

If you want to keep both apps as separate codebases but serve them from the same port, Nginx reverse proxy is perfect. Here’s how to set it up on Ubuntu 16.04:

  • Prepare your existing apps
    Modify each app’s server code to listen only on localhost (so they’re not accessible directly from outside):

    // In calendar app's server.js
    app.listen(3000, '127.0.0.1', () => {
      console.log('Calendar app running on localhost:3000');
    });
    
    // In todo app's server.js
    app.listen(3001, '127.0.0.1', () => {
      console.log('Todo app running on localhost:3001');
    });
    
  • Install Nginx
    Run these commands to install and start Nginx:

    sudo apt-get update && sudo apt-get install nginx
    sudo systemctl start nginx
    
  • Configure reverse proxy

    1. Create a new Nginx config file:
      sudo nano /etc/nginx/sites-available/mean-combined
      
    2. Paste this configuration (adjust paths if your apps use HTML5 routing):
      server {
          listen 3002;
          server_name localhost;
      
          # Route for calendar app
          location /calendar {
              proxy_pass http://127.0.0.1:3000;
              proxy_set_header Host $host;
              proxy_set_header X-Real-IP $remote_addr;
              # Fix Angular HTML5 mode refresh issues
              try_files $uri $uri/ /calendar/index.html;
          }
      
          # Route for todo app
          location /todo {
              proxy_pass http://127.0.0.1:3001;
              proxy_set_header Host $host;
              proxy_set_header X-Real-IP $remote_addr;
              try_files $uri $uri/ /todo/index.html;
          }
      
          # Main landing page with navigation links
          location / {
              root /var/www/html;
              index index.html;
          }
      }
      
    3. Enable the config and restart Nginx:
      sudo ln -s /etc/nginx/sites-available/mean-combined /etc/nginx/sites-enabled/
      sudo nginx -t # Test config for errors
      sudo systemctl restart nginx
      
  • Add a navigation landing page
    Create a simple index.html in /var/www/html to let users switch between apps:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Combined MEAN Apps</title>
    </head>
    <body>
        <h1>My Apps</h1>
        <ul>
            <li><a href="/calendar">Calendar App</a></li>
            <li><a href="/todo">Todo List</a></li>
        </ul>
    </body>
    </html>
    
Key Notes
  • Database connections: If both apps use separate MongoDB databases, make sure their connection strings are correctly configured in either the main project’s .env file or the individual app’s configs.
  • Port conflicts: Ensure no other service is using port 3002 on your Ubuntu machine. Check with sudo lsof -i :3002 and kill any conflicting processes if needed.
  • Production readiness: For production, consider adding SSL certificates (with Let’s Encrypt) and setting up process managers like pm2 to keep your apps running in the background.

内容的提问来源于stack exchange,提问作者Jordan Green

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:32:59