作为一名全栈开发者,最近完成了一个宠物用品商城系统的开发。这个项目采用前后端分离架构,后端基于Node.js的Express框架,前端使用Vue.js构建。整个系统从零开始搭建,历时两个月完成,现在把开发过程中的关键技术和经验分享给大家。
这个商城系统包含了完整的电商功能模块:用户注册登录、商品展示、购物车管理、订单处理等。特别针对宠物用品行业的特点,我们还增加了宠物档案管理、智能推荐等特色功能。系统上线后运行稳定,日均PV达到5000+,经受住了实际业务的考验。
后端选择Node.js主要基于以下几个考虑:
具体技术栈:
提示:Express虽然轻量,但对于大型项目建议考虑Koa或NestJS,它们提供了更好的中间件管理和TypeScript支持。
前端采用Vue 3组合式API开发,主要技术组件:
选择Vite而非Webpack主要看中其极快的启动和热更新速度,特别是在大型项目中优势明显。实测项目冷启动时间从Webpack的45秒缩短到Vite的1.3秒。
采用JWT实现无状态认证,关键实现点:
javascript复制// JWT签发
const token = jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '7d' }
);
// 认证中间件
const auth = async (req, res, next) => {
try {
const token = req.header('Authorization').replace('Bearer ', '');
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findByPk(decoded.userId);
next();
} catch (e) {
res.status(401).send({ error: '请先登录' });
}
};
安全注意事项:
商品表核心字段设计:
sql复制CREATE TABLE `products` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`price` decimal(10,2) NOT NULL,
`stock` int NOT NULL DEFAULT '0',
`category_id` int NOT NULL,
`description` text,
`cover_image` varchar(255) DEFAULT NULL,
`detail_images` json DEFAULT NULL,
`specs` json DEFAULT NULL,
`sales` int DEFAULT '0',
`status` tinyint DEFAULT '1',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `category_id` (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
性能优化措施:
购物车数据结构设计考虑:
核心API示例:
javascript复制router.post('/cart', auth, async (req, res) => {
const { productId, quantity, specs } = req.body;
// 查找是否已存在相同商品
let cartItem = await Cart.findOne({
where: {
userId: req.user.id,
productId
}
});
if (cartItem) {
// 更新数量
cartItem.quantity += quantity;
await cartItem.save();
} else {
// 新增记录
cartItem = await Cart.create({
userId: req.user.id,
productId,
quantity,
specs
});
}
res.send(cartItem);
});
使用WebSocket实现订单状态实时推送:
javascript复制// WebSocket服务
const wss = new WebSocket.Server({ port: 8081 });
wss.on('connection', (ws) => {
ws.on('message', (message) => {
const { userId, type } = JSON.parse(message);
// 订阅用户专属频道
if (type === 'subscribe') {
ws.userId = userId;
}
});
});
// 订单状态变更时
function notifyOrderUpdate(userId, order) {
wss.clients.forEach((client) => {
if (client.userId === userId) {
client.send(JSON.stringify({
type: 'orderUpdate',
data: order
}));
}
});
}
前端优化:
后端优化:
监控告警:
后端Dockerfile示例:
dockerfile复制FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
使用docker-compose编排服务:
yaml复制version: '3'
services:
app:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
depends_on:
- redis
- mysql
redis:
image: redis:6-alpine
ports:
- "6379:6379"
mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: pet_store
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
volumes:
mysql_data:
GitHub Actions自动化部署配置:
yaml复制name: Deploy to Production
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Login to Docker Hub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v2
with:
push: true
tags: yourusername/pet-store:latest
- name: Deploy to Server
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SERVER_SSH_KEY }}
script: |
docker-compose pull
docker-compose up -d
数据库设计:
错误处理:
javascript复制app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
code: err.code || 500,
message: err.message || 'Internal Server Error',
data: null
});
});
安全防护:
性能调优:
这个项目让我对全栈开发有了更深入的理解,特别是在性能优化和安全防护方面积累了不少实战经验。对于想学习Node.js和Vue.js的开发者,建议从小项目开始,逐步掌握各项技术,最终能够构建出像这样完整的商业系统。