返回

简洁的 Vue + Node + MongoDB 个人博客系统指南

前端

前言

随着数字时代的到来,个人博客系统越来越受到欢迎,它可以让您轻松地分享您的想法、观点和经验,也可以作为您的线上日记本,记录下生活中的美好瞬间。如果您也想搭建自己的个人博客系统,那么本文将为您提供一份详细的指南,我们将使用 Vue、Node.js 和 MongoDB 来构建一个简约且功能齐全的个人博客系统。

准备工作

在开始之前,请确保您已安装以下软件:

  • Node.js v12 或更高版本
  • MongoDB v4.0 或更高版本
  • Vue CLI
  • Git

项目结构

项目结构如下:

├── client
│   ├── src
│   │   ├── App.vue
│   │   ├── components
│   │   ├── pages
│   │   ├── router.js
│   │   ├── store
│   │   └── main.js
│   ├── public
│   │   ├── index.html
│   │   ├── favicon.ico
│   │   └── manifest.json
│   ├── package.json
│   ├── .gitignore
│   └── yarn.lock
├── server
│   ├── src
│   │   ├── app.js
│   │   ├── controllers
│   │   ├── models
│   │   ├── routes
│   │   ├── services
│   │   └── utils
│   ├── package.json
│   ├── .gitignore
│   └── yarn.lock
├── .env
├── README.md
├── package.json
└── yarn.lock

搭建前后端架构

首先,我们将使用 Vue CLI 来创建一个 Vue 项目,并使用 Express 作为 Node.js 服务器。

  1. 在项目根目录下运行以下命令:
vue create client
cd client
  1. 选择 "Default (Vue 3)" 选项,然后按回车键。

  2. 等待项目安装完成。

  3. 在项目根目录下运行以下命令:

npm install express mongoose body-parser
  1. server 文件夹中创建一个新的文件 app.js,并添加以下代码:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.json());

mongoose.connect('mongodb://localhost:27017/blog', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('Connected to MongoDB');
});

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});
  1. client 文件夹中创建一个新的文件 main.js,并添加以下代码:
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app');
  1. client 文件夹中创建一个新的文件 router.js,并添加以下代码:
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './pages/Home.vue';
import About from './pages/About.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
];

const router = new VueRouter({
  routes
});

export default router;
  1. client 文件夹中创建一个新的文件 store.js,并添加以下代码:
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  }
});

export default store;
  1. client 文件夹中的 public 文件夹中创建一个新的文件 index.html,并添加以下代码:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
</head>
<body>
  <div id="app"></div>
  <script src="js/app.js"></script>
</body>
</html>
  1. 在项目根目录下运行以下命令:
npm run serve
  1. 打开浏览器,访问 http://localhost:8080,您将看到以下页面:
Hello World!

创建文章、标签、搜索和留言功能

接下来,我们将为我们的博客系统添加文章、标签、搜索和留言功能。

  1. server 文件夹中的 models 文件夹中创建一个新的文件 Article.js,并添加以下代码:
const mongoose = require('mongoose');

const ArticleSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  content: {
    type: String,
    required: true
  },
  tags: {
    type: [String],
    required: true
  },
  author: {
    type: String,
    required: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

const Article = mongoose.model('Article', ArticleSchema);

module.exports = Article;
  1. server 文件夹中的 controllers 文件夹中创建一个新的文件 ArticlesController.js,并添加以下代码:
const Article = require('../models/Article');

const ArticlesController = {
  create: async (req, res) => {
    const article = new Article(req.body);
    await article.save();
    res.send(article);
  },
  getAll: async (req, res) => {
    const articles = await Article.find();
    res.send(articles);
  },
  getById: async (req, res) => {
    const article = await Article.findById(req.params.id);
    res.send(article);
  },
  update: async (req, res) => {
    const article = await Article.findByIdAndUpdate(req.params.id, req.body, { new: true });
    res.send(article);
  },
  delete: async (req, res) => {
    await Article.findByIdAndDelete(req.params.id);
    res.send({ message: 'Article deleted successfully' });
  }
};

module.exports = ArticlesController;
  1. server 文件夹中的 routes 文件夹中创建一个新的文件 articles.js,并添加以下代码:
const express = require('express');
const router = express.Router();
const ArticlesController = require('../controllers/ArticlesController');

router.post('/', ArticlesController.create);
router.get('/', ArticlesController.getAll);
router.get('/:id', ArticlesController.getById);
router.put('/:id', ArticlesController.update);
router.delete('/:id', ArticlesController.delete);

module.exports = router;
  1. server 文件夹中的 app.js 文件中,添加以下代码:
const articlesRouter = require('./routes/articles');

app.use('/articles', articlesRouter);
  1. client 文件夹中的 components 文件夹中创建一个新的文件 ArticleForm.vue,并添加以下代码:
<template>
  <form @submit