一個 Vue + Node + MongoDB 博客系統


源碼

耗時半載(半個月)的大項目終於完成了。這是一個博客系統,使用 Vue 做前端框架,Node + express 做后端,數據庫使用的是 MongoDB。實現了用戶注冊、用戶登錄、博客管理(文章的修改和刪除)、文章編輯(Markdown)、標簽分類等功能。

很早之前就想寫一個個人博客。學了 Vue 之后,把前端部分寫出來,然后 Node 一直拖拖拉拉的學了很久,中間又跑去實習了一段時間,所以直到回學校之后才列了個計划把這個項目實現了。

翻出之前寫的前端部分,好丑啊,干脆推掉重寫吧。前端模仿的是 hexo 的經典主題 NexT ,本來是想把源碼直接拿過來用的,后來發現還不如自己寫來得快,就全部自己動手實現成 vue components。

實現的功能

  1. 文章的編輯,修改,刪除
  2. 支持使用 Markdown 編輯與實時預覽
  3. 支持代碼高亮
  4. 給文章添加標簽
  5. 支持用戶注冊登錄

使用到的技術

前端

  1. Vue.js
  2. vue-cli
  3. vue-router
  4. vue-resource
  5. element-ui
  6. marked
  7. highlight.js

后端

  1. Node.js
  2. Express
  3. Mongoose

基本思路

前端使用 vue-router 操作路由,實現單頁應用的效果。使用 vue-resource 從后台獲取數據,數據的處理全部都在前端,所以后端要做的事情很簡單——把前端打包好的數據存進數據庫中和從數據庫中取出數據。前后端使用統一的路由命名規則。

項目目錄

| app.js              后端入口
| index.html          入口頁面
| .babelrc            babel配置
| .gitignore          git配置
| package.json
| webpack.config.js   webpack配置
|
|-dist                vue打包生成的文件
|
|-node_modules        模塊
|
|-server              后端
    | check.js
    | db.js           數據庫
 __| router.js       路由
|
|-src                 前端
    |-assets          靜態資源
    |-components      組件
    | App.vue
    | main.js

webpack 配置

webpack 大部分是 vue-cli 自動生成的,添加了讓前后端http請求都轉到node的3000端口,而不是前端的8080端口的配置。

devServer: {
    historyApiFallback: true,
    noInfo: true,

    //讓前后端http請求都轉到node的3000端口,而不是前端的8080端口
    proxy: {
      '/': {
        target: 'http://localhost:3000/'
      }
    }
  }

這里涉及一個新手可能會不明白的問題(我之前就搗鼓了半天)。

開發的時候要先打開數據庫 MongoDB ,使用命令 mongod

然后打開后端服務器 node app,后端監聽 3000 端口。

最后打開前端開發模式 npm run dev,前端啟動了一個 webpack 服務器,監聽 8080 端口用於熱刷新。通過配置把前端的http請求轉到 3000 端口。

前端部分

命名視圖

所有頁面都用到的元素可以寫在 App.vue 上面,也可以寫成公共組件。我在 App.vue 中使用了命名視圖,因為 sidebar 這個組件有的頁面需要有的不需要,不需要的時候就不用加載。

<!--App.vue-->
<template>
  <div id="app">
    <div class="black_line"></div>
    <div id="main">
      <router-view name="sidebar"></router-view>
      <router-view></router-view>
    </div>
  </div>
</template>

router

路由的配置寫在 main.js 中,分為前台展示和后台管理。后台管理統一以 ‘/admin’ 開頭。注冊頁和登錄頁寫在一起了,上面有兩個按鈕“注冊”和“登錄”(我好懶-_-)。

// main.js
const router = new VueRouter({
  routes: [
    {path: '/', components: {default: article, sidebar: sidebar}},
    {path: '/article', components: {default: article, sidebar: sidebar}},
    {path: '/about', components: {default: about, sidebar: sidebar}},
    {path: '/articleDetail/:id', components: {default: articleDetail, sidebar: sidebar}},
    {path: '/admin/articleList', components: {default: articleList, sidebar: sidebar}},
    {path: '/admin/articleEdit', component: articleEdit},
    {path: '/admin/articleEdit/:id', component: articleEdit},
    {path: '/admin/signin', component: signin}
  ]
})

element UI

使用了 element 用於消息提醒和標簽分類。並不需要整個引入,而是使用按需引入。

// main.js
// 按需引用element
import { Button, Message, MessageBox, Notification, Popover, Tag, Input } from 'element-ui'
import 'element-ui/lib/theme-default/index.css'

const components = [Button, Message, MessageBox, Notification, Popover, Tag, Input]

components.forEach((item) => {
  Vue.component(item.name, item)
})

const MsgBox = MessageBox
Vue.prototype.$msgbox = MsgBox
Vue.prototype.$alert = MsgBox.alert
Vue.prototype.$confirm = MsgBox.confirm
Vue.prototype.$prompt = MsgBox.prompt
Vue.prototype.$message = Message
Vue.prototype.$notify = Notification

vue-resource

用於向后端發起請求。打通前后端的關鍵。

// GET /someUrl
  this.$http.get('/someUrl').then(response => {
    // success callback
  }, response => {
    // error callback
  });

get 請求

前端發起 get 請求,當請求成功被返回執行第一個回調函數,請求沒有被成功返回則執行第二個回調函數。

this.$http.get('/api/articleDetail/' + id).then(
  response => this.article = response.body,
  response => console.log(response)
)

后端響應請求並返回結果

// router.js
router.get('/api/articleDetail/:id', function (req, res) {
  db.Article.findOne({ _id: req.params.id }, function (err, docs) {
    if (err) {
      console.error(err)
      return
    }
    res.send(docs)
  })
})

post 請求

前端發起 post 請求,當請求成功被返回執行第一個回調函數,請求沒有被成功返回則執行第二個回調函數。

// 新建文章
// 即將被儲存的數據 obj
let obj = {
  title: this.title,
  date: this.date,
  content: this.content,
  gist: this.gist,
  labels: this.labels
}
this.$http.post('/api/admin/saveArticle', {
  articleInformation: obj
}).then(
  response => {
    self.$message({
      message: '發表文章成功',
      type: 'success'
    })
    // 保存成功后跳轉至文章列表頁
    self.refreshArticleList()
  },
  response => console.log(response)
)

后端存儲數據並返回結果

// router.js
// 文章保存
router.post('/api/admin/saveArticle', function (req, res) {
  new db.Article(req.body.articleInformation).save(function (err) {
    if (err) {
      res.status(500).send()
      return
    }
    res.send()
  })
})

后端部分

后端使用 express 構建了一個簡單的服務器,幾乎只用於操作數據庫。

app.js 位於項目根目錄,使用 node app 運行服務器。

const express = require('express')
const fs = require('fs')
const path = require('path')
const bodyParse = require('body-parser')
const session = require('express-session')
const MongoStore = require('connect-mongo')(session)
const router = require('./server/router')
const app = express()

const resolve = file => path.resolve(__dirname, file)

app.use('/dist', express.static(resolve('./dist')))
app.use(bodyParse.json())
app.use(bodyParse.urlencoded({ extended: true }))
app.use(router)

// session
app.set('trust proxy', 1) // trust first proxy
app.use(session({
  secret: 'blog',
  resave: false,
  saveUninitialized: true,
  cookie: {
    secure: true,
    maxAge: 2592000000
  },
  store: new MongoStore({
    url: 'mongodb://localhost:27017/blog'
  })
}))

app.get('*', function (req, res) {
  let html = fs.readFileSync(resolve('./' + 'index.html'), 'utf-8')
  res.send(html)
})

app.listen(3000, function () {
  console.log('訪問地址為 localhost:3000')
})

給自己挖了一個坑。因為登錄之后需要保存用戶狀態,用來判斷用戶是否登錄,如果登錄則可以進入后台管理,如果沒有登錄則不能進入后台管理頁面。之前寫 node 的時候用的是 session 來保存,不過spa應用不同於前后端不分離的應用,我在前端對用戶輸入的賬號密碼進行了判斷,如果成功則請求登錄在后端保存 session。不過不知道出於什么原因,session 總是沒辦法賦值。因為我 node 學的也是半吊子,所以暫時放着,等我搞清楚了再來填坑。

收獲

  1. 學一個新模塊,新框架第一步就是閱讀官方文檔。
  2. 不要覺得讀文檔費時間,認真的讀一遍官方文檔比你瞎折騰來得有效率。
  3. 閱讀與你項目相關的優秀項目的源碼,學習別人如何組織代碼。
  4. 自己的解決方案不一定是最優解,不過在找到最優解之前不妨自己先試試。
  5. 框架模塊的使用都不難,套API的活每個人都能干,只是快與慢的差別。
  6. 嘗試思考這個API是如何實現的。
  7. 了解了完整的web應用是如何運作的,包括服務器,數據庫,前端是如何聯系在一起的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM