如何在本地同一端口运行两个React项目以共享localStorage?
本地同一端口运行多React项目的解决方案
方法1:基于Express的自定义代理服务器
这是最灵活的方案,适合需要精细控制路由转发的场景:
- 分别启动两个React项目的开发服务器:
- 应用A:执行
npm start(假设默认运行在http://localhost:8001) - 应用B:修改其
package.json里的start命令为PORT=8002 react-scripts start,启动后运行在http://localhost:8002
- 应用A:执行
- 新建空文件夹,初始化Node项目:
npm init -y,安装依赖:npm install express http-proxy-middleware - 创建
server.js文件,写入以下代码:const express = require('express'); const { createProxyMiddleware } = require('http-proxy-middleware'); const app = express(); // 转发/appA开头的请求到应用A的开发服务器 app.use('/appA', createProxyMiddleware({ target: 'http://localhost:8001', changeOrigin: true, pathRewrite: { '^/appA': '' } // 去掉路径前缀,让应用A能正确处理路由 })); // 转发/appB开头的请求到应用B的开发服务器 app.use('/appB', createProxyMiddleware({ target: 'http://localhost:8002', changeOrigin: true, pathRewrite: { '^/appB': '' } })); // 监听8001端口(确保该端口未被占用) app.listen(8001, () => { console.log('代理服务器运行在 http://localhost:8001'); }); - 启动代理服务器:
node server.js,之后访问http://localhost:8001/appA打开应用A,http://localhost:8001/appB打开应用B,两者共享同一端口的localStorage - 关键配置:两个React应用的路由需设置
basename,比如应用A的路由组件:
应用B同理设置<BrowserRouter basename="/appA"> {/* 路由配置 */} </BrowserRouter>basename="/appB",确保路由跳转正常
方法2:利用Create React App的内置代理(适合单主应用场景)
如果其中一个应用可作为入口,用CRA内置代理简化配置:
- 启动应用B的开发服务器在8002(同方法1)
- 修改应用A的
package.json,添加代理配置:"proxy": { "/appB": { "target": "http://localhost:8002", "pathRewrite": { "^/appB": "" } } } - 重启应用A的开发服务器(默认8001),访问
http://localhost:8001/appB即可打开应用B,同样需给应用B的路由设置basename="/appB"
方法3:本地Nginx反向代理
若已安装Nginx,可通过配置反向代理实现:
- 启动两个React应用的开发服务器在8001和8002
- 找到Nginx配置文件(如
/usr/local/etc/nginx/nginx.conf或/etc/nginx/nginx.conf),添加以下server块:server { listen 8001; server_name localhost; location /appA/ { proxy_pass http://localhost:8001/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } location /appB/ { proxy_pass http://localhost:8002/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; rewrite ^/appB/(.*)$ /$1 break; } } - 重启Nginx:
sudo nginx -s reload,之后访问http://localhost:8001/appA和http://localhost:8001/appB即可
所有方案均无需构建部署,修改代码后React开发服务器会自动热更新,满足本地测试需求的同时,共享同一端口的localStorage以解决认证跳转问题。
内容的提问来源于stack exchange,提问作者Mohit Chauhan
相关产品推荐
相关产品推荐

