在现代 Web 项目中,前后端分离的架构已经成为主流选择。本篇文章将带你从零开始,构建一个完整的博客系统,涵盖前后端架构设计、数据库建模、接口开发与前端页面集成,帮助你更全面地掌握全栈开发技能。
📌 技术栈选型
- 前端框架:Vue3 + Vite + Element Plus
- 后端框架:Express + Node.js
- 数据库:MongoDB + Mongoose
- 接口设计:RESTful API
- 工具链:Postman、Nodemon、MongoDB Compass
🗂 项目结构预览
perl
perl
复制编辑
blog-system/
├── client/ # 前端项目(Vue3)
└── server/ # 后端项目(Node.js + MongoDB)
🧱 后端项目搭建(Node.js)
1. 初始化项目
bash
bash
复制编辑
mkdir server && cd server
npm init -y
npm install express mongoose cors body-parser
2. 建立数据库连接
php
js
复制编辑
// db.js
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/blog', {
useNewUrlParser: true,
useUnifiedTopology: true
})
3. 创建数据模型(Mongoose)
javascript
js
复制编辑
// models/Post.js
const mongoose = require('mongoose')
const PostSchema = new mongoose.Schema({
title: String,
content: String,
createdAt: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('Post', PostSchema)
4. 搭建基础接口
javascript
js
复制编辑
// server.js
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const Post = require('./models/Post')
mongoose.connect('mongodb://localhost:27017/blog')
const app = express()
app.use(cors())
app.use(express.json())
// 获取文章列表
app.get('/api/posts', async (req, res) => {
const posts = await Post.find().sort({ createdAt: -1 })
res.json(posts)
})
// 创建新文章
app.post('/api/posts', async (req, res) => {
const newPost = await Post.create(req.body)
res.json(newPost)
})
app.listen(3000, () => console.log('Server running on http://localhost:3000'))
🖼 前端项目搭建(Vue3 + Vite)
sql
bash
复制编辑
npm create vite@latest client --template vue
cd client
npm install axios element-plus
示例页面:文章列表
xml
vue
复制编辑
<template>
<el-container>
<el-main>
<el-card v-for="post in posts" :key="post._id" class="mb-4">
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
</el-card>
</el-main>
</el-container>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import axios from 'axios'
const posts = ref([])
onMounted(async () => {
const res = await axios.get('http://localhost:3000/api/posts')
posts.value = res.data
})
</script>
🚀 页面扩展建议
- ✅ 添加富文本编辑器(如:quill、wangEditor)
- 🔐 添加用户认证模块(JWT)
- 🧩 增加评论、标签、分类等功能
- 📦 添加 markdown 支持,适配写作体验
✅ 项目总结
这个简单的博客系统演示了从数据库建模到 RESTful 接口,再到 Vue3 前端集成的全过程,是一个很适合作为全栈入门的实战项目。同时,它也为更复杂的后台管理系统打下了良好的架构基础。