一、全栈开发技术栈选型与架构设计
现代Web开发已形成”前端框架+后端服务+云基础设施”的标准化技术栈。Vue.js凭借其渐进式架构和响应式数据绑定机制,成为前端开发的优选方案;Node.js的非阻塞I/O模型则完美契合高并发服务端场景。两者通过JSON格式的API进行数据交互,形成典型的前后端分离架构。
核心组件选型原则:
- 前端框架:Vue 3组合式API + Pinia状态管理
- 后端框架:Express.js(轻量级)或 NestJS(企业级)
- 数据库:MongoDB(文档型)或 PostgreSQL(关系型)
- 构建工具:Vite(前端) + Webpack(复杂项目)
- 部署方案:Nginx反向代理 + PM2进程管理
示例项目架构图:
客户端浏览器 → Nginx(负载均衡) → Node.js集群 → MongoDB集群↑CDN加速(静态资源)
二、开发环境搭建与工程化配置
1. 基础环境准备
- Node.js环境:推荐使用nvm管理多版本,开发环境采用LTS版本(如18.x)
- 包管理工具:npm或yarn,建议配置
package-lock.json锁定依赖版本 - 代码编辑器:VS Code配置ESLint+Prettier统一代码风格
2. 项目初始化
# 前端项目初始化npm create vue@latest my-vue-appcd my-vue-appnpm install axios vue-router pinia# 后端项目初始化mkdir my-node-server && cd my-node-servernpm init -ynpm install express mongoose cors dotenv
3. 关键配置文件
.env环境变量管理(区分development/production模式)vue.config.js前端构建配置(代理设置、打包优化)ecosystem.config.jsPM2进程管理配置
三、核心模块开发实战
1. 后端API开发
Express中间件链设计:
// app.js 核心中间件配置const express = require('express');const app = express();// 基础中间件app.use(express.json());app.use(cors());app.use(require('./middleware/logger'));// 路由模块app.use('/api/auth', require('./routes/auth'));app.use('/api/products', require('./routes/products'));// 错误处理中间件app.use((err, req, res, next) => {console.error(err.stack);res.status(500).json({ error: 'Internal Server Error' });});
RESTful API设计规范:
- 资源命名使用复数名词(如
/users) - 使用HTTP方法明确操作类型(GET/POST/PUT/DELETE)
- 统一响应格式:
{"code": 200,"message": "success","data": { ... }}
2. 前端组件开发
Vue 3组合式API示例:
<script setup>import { ref, onMounted } from 'vue';import { getProducts } from '@/api/products';const products = ref([]);const loading = ref(false);onMounted(async () => {try {loading.value = true;const res = await getProducts();products.value = res.data;} finally {loading.value = false;}});</script><template><div v-if="loading">Loading...</div><ul v-else><li v-for="item in products" :key="item.id">{{ item.name }} - ¥{{ item.price }}</li></ul></template>
3. 状态管理与权限控制
Pinia状态管理实践:
// stores/auth.jsimport { defineStore } from 'pinia';export const useAuthStore = defineStore('auth', {state: () => ({token: null,userInfo: null}),actions: {async login(credentials) {const res = await api.login(credentials);this.token = res.data.token;this.userInfo = res.data.user;localStorage.setItem('token', this.token);},logout() {this.$reset();localStorage.removeItem('token');}}});
JWT权限验证中间件:
// middleware/auth.jsmodule.exports = (req, res, next) => {const token = req.headers['authorization']?.split(' ')[1];if (!token) return res.status(401).json({ error: 'Unauthorized' });try {const decoded = jwt.verify(token, process.env.JWT_SECRET);req.user = decoded;next();} catch (err) {res.status(403).json({ error: 'Invalid Token' });}};
四、项目部署与运维方案
1. 云服务器准备
- 选购主流云服务商的2核4G实例(建议选择按流量计费模式)
- 操作系统选择Ubuntu 22.04 LTS
- 安全组配置开放80/443/22端口
2. 自动化部署流程
部署脚本示例:
#!/bin/bash# 更新系统apt update && apt upgrade -y# 安装Node.js环境curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -apt install -y nodejs nginx# 前端构建cd /var/www/my-app/clientnpm installnpm run build# 后端部署cd /var/www/my-app/servernpm install --productionpm2 restart ecosystem.config.js# Nginx配置cat > /etc/nginx/sites-available/my-app <<EOFserver {listen 80;server_name example.com;location / {root /var/www/my-app/client/dist;try_files \$uri \$uri/ /index.html;}location /api/ {proxy_pass http://localhost:3000;proxy_set_header Host \$host;}}EOFnginx -t && systemctl restart nginx
3. 运维监控体系
- 日志管理:使用
winston+logrotate实现日志分割 - 性能监控:集成
PM2 Plus或第三方APM工具 - 告警机制:配置
Uptime Robot进行可用性监控
五、持续集成与版本控制
Git工作流规范:
-
主分支策略:
main:生产环境代码develop:开发主分支feature/*:功能开发分支release/*:预发布分支
-
提交规范:
```
():
示例
feat(api): 添加用户注册接口
fix(auth): 修复JWT过期处理逻辑
**CI/CD配置示例**:```yaml# .github/workflows/deploy.ymlname: Deploy to Productionon:push:branches: [ main ]jobs:deploy:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v3- name: Install dependenciesrun: |cd servernpm ci- name: Deploy to Serveruses: appleboy/ssh-action@masterwith:host: ${{ secrets.SERVER_IP }}username: ${{ secrets.SERVER_USER }}key: ${{ secrets.SSH_PRIVATE_KEY }}script: |cd /var/www/my-appgit pull origin maincd server && npm install --production && pm2 restart all
六、开发过程中的常见问题解决方案
-
跨域问题处理:
- 开发环境配置代理:
// vue.config.jsmodule.exports = {devServer: {proxy: {'/api': {target: 'http://localhost:3000',changeOrigin: true}}}}
- 开发环境配置代理:
-
JWT存储安全:
- 避免使用
localStorage存储敏感token - 推荐使用
httpOnly的Cookie或secure+sameSite属性
- 避免使用
-
MongoDB连接优化:
- 使用连接池管理数据库连接
- 配置合理的
maxPoolSize参数(通常设置为CPU核心数的2倍)
-
前端性能优化:
- 路由懒加载:
const UserList = () => import('@/views/UserList.vue')
- 图片资源使用CDN加速
- 开启Gzip压缩(Nginx配置)
- 路由懒加载:
七、进阶学习建议
- 深入理解Node.js事件循环机制
- 学习Vue 3的响应式原理与编译优化
- 掌握MongoDB的聚合管道与索引优化
- 研究容器化部署方案(Docker+Kubernetes)
- 了解Serverless架构在全栈开发中的应用
通过系统掌握本文介绍的技术栈和开发实践,开发者能够独立构建并部署生产级别的Web应用。建议结合实际项目需求,逐步完善技术方案,同时关注社区最新动态(如Vue 3.4的新特性、Node.js的稳定性更新等),保持技术栈的持续优化。