nodejs 如何架构react
使用 Node.js 架构 React 应用
Node.js 可以作为 React 应用的开发服务器和构建工具,同时支持后端 API 开发。以下是常见的架构方法:
使用 Vite 构建工具
安装 Vite 作为 React 的开发服务器和构建工具:
npm create vite@latest my-react-app --template react
cd my-react-app
npm install
npm run dev
Vite 提供极快的开发服务器和优化的生产构建,适合现代 React 应用开发。
使用 Express 作为后端 API
创建 Express 后端服务与 React 前端配合:
mkdir server
cd server
npm init -y
npm install express
创建 server.js 文件:

const express = require('express');
const app = express();
const PORT = 3001;
app.get('/api/data', (req, res) => {
res.json({ message: 'Hello from Express!' });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
配置代理解决跨域
在 React 项目的 vite.config.js 中添加代理配置:
export default defineConfig({
server: {
proxy: {
'/api': 'http://localhost:3001'
}
}
})
生产环境部署
构建 React 应用并配置 Express 托管静态文件:
npm run build
修改 server.js 添加静态文件服务:

const path = require('path');
app.use(express.static(path.join(__dirname, '../dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../dist', 'index.html'));
});
使用 Next.js 全栈方案
Next.js 提供 React 全栈解决方案:
npx create-next-app@latest
Next.js 内置 API 路由功能,可直接在 pages/api 目录下创建后端接口,无需单独配置 Node.js 服务器。
数据库集成
添加数据库连接(以 MongoDB 为例):
npm install mongoose
在 Express 中连接数据库:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/react-app');





