如何将两款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:
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 dotenvMerge frontend code (Angular)
- Build both your calendar and todo apps using
ng build(if using Angular CLI) to generate production-ready static files. - Move the
distfolders of both apps into the main project’s static directory (or combine them into a singledistfolder with subdirectories likedist/calendaranddist/todo). - 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 { } - 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>
- Build both your calendar and todo apps using
Merge backend APIs
- Copy the route files from both apps into the main project’s
routesdirectory. - Import these routes into your main
server.jsand 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'); });
- Copy the route files from both apps into the main project’s
Resolve dependency conflicts
Check thepackage.jsonfiles of both original apps, and make sure all shared dependencies (likeexpress,mongoose,@angular/core) use compatible versions in the main project. Runnpm installto sync dependencies.
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 onlocalhost(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 nginxConfigure reverse proxy
- Create a new Nginx config file:
sudo nano /etc/nginx/sites-available/mean-combined - 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; } } - 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
- Create a new Nginx config file:
Add a navigation landing page
Create a simpleindex.htmlin/var/www/htmlto 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>
- Database connections: If both apps use separate MongoDB databases, make sure their connection strings are correctly configured in either the main project’s
.envfile 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 :3002and kill any conflicting processes if needed. - Production readiness: For production, consider adding SSL certificates (with Let’s Encrypt) and setting up process managers like
pm2to keep your apps running in the background.
内容的提问来源于stack exchange,提问作者Jordan Green

