利用Vue.js+Node.js+MongoDB實(shí)現(xiàn)一個(gè)博客系統(tǒng)(附源碼)
前言
這篇文章實(shí)現(xiàn)的博客系統(tǒng)使用 Vue 做前端框架,Node + express 做后端,數(shù)據(jù)庫使用的是 MongoDB。實(shí)現(xiàn)了用戶注冊、用戶登錄、博客管理(文章的修改和刪除)、文章編輯(Markdown)、標(biāo)簽分類等功能。
前端模仿的是 hexo 的經(jīng)典主題 NexT ,本來是想把源碼直接拿過來用的,后來發(fā)現(xiàn)還不如自己寫來得快,就全部自己動(dòng)手實(shí)現(xiàn)成 vue components。
實(shí)現(xiàn)的功能
1.文章的編輯,修改,刪除
2.支持使用 Markdown 編輯與實(shí)時(shí)預(yù)覽
3.支持代碼高亮
4.給文章添加標(biāo)簽
5.支持用戶注冊登錄
使用到的技術(shù)
前端
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 操作路由,實(shí)現(xiàn)單頁應(yīng)用的效果。使用 vue-resource 從后臺(tái)獲取數(shù)據(jù),數(shù)據(jù)的處理全部都在前端,所以后端要做的事情很簡單——把前端打包好的數(shù)據(jù)存進(jìn)數(shù)據(jù)庫中和從數(shù)據(jù)庫中取出數(shù)據(jù)。前后端使用統(tǒng)一的路由命名規(guī)則。
項(xiàng)目目錄
| app.js 后端入口 | index.html 入口頁面 | .babelrc babel配置 | .gitignore git配置 | package.json | webpack.config.js webpack配置 | |-dist vue打包生成的文件 | |-node_modules 模塊 | |-server 后端 | check.js | db.js 數(shù)據(jù)庫 __| router.js 路由 | |-src 前端 |-assets 靜態(tài)資源 |-components 組件 | App.vue | main.js
webpack 配置
webpack 大部分是 vue-cli 自動(dòng)生成的,添加了讓前后端http請求都轉(zhuǎn)到node的3000端口,而不是前端的8080端口的配置。
devServer: {
historyApiFallback: true,
noInfo: true,
//讓前后端http請求都轉(zhuǎn)到node的3000端口,而不是前端的8080端口
proxy: {
'/': {
target: 'http://localhost:3000/'
}
}
}
這里涉及一個(gè)新手可能會(huì)不明白的問題(我之前就搗鼓了半天)。
開發(fā)的時(shí)候要先打開數(shù)據(jù)庫 MongoDB ,使用命令 mongod。
然后打開后端服務(wù)器 node app,后端監(jiān)聽 3000 端口。
最后打開前端開發(fā)模式 npm run dev,前端啟動(dòng)了一個(gè) webpack 服務(wù)器,監(jiān)聽 8080 端口用于熱刷新。通過配置把前端的http請求轉(zhuǎn)到 3000 端口。
前端部分
命名視圖
所有頁面都用到的元素可以寫在 App.vue 上面,也可以寫成公共組件。我在 App.vue 中使用了命名視圖,因?yàn)?sidebar 這個(gè)組件有的頁面需要有的不需要,不需要的時(shí)候就不用加載。
<!--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 中,分為前臺(tái)展示和后臺(tái)管理。后臺(tái)管理統(tǒng)一以 ‘/admin' 開頭。注冊頁和登錄頁寫在一起了,上面有兩個(gè)按鈕“注冊”和“登錄”(我好懶-_-)。
// 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 用于消息提醒和標(biāo)簽分類。并不需要整個(gè)引入,而是使用按需引入。
// 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
用于向后端發(fā)起請求。打通前后端的關(guān)鍵。
// GET /someUrl
this.$http.get('/someUrl').then(response => {
// success callback
}, response => {
// error callback
});
get 請求
前端發(fā)起 get 請求,當(dāng)請求成功被返回執(zhí)行第一個(gè)回調(diào)函數(shù),請求沒有被成功返回則執(zhí)行第二個(gè)回調(diào)函數(shù)。
this.$http.get('/api/articleDetail/' + id).then(
response => this.article = response.body,
response => console.log(response)
)
后端響應(yīng)請求并返回結(jié)果
// 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 請求
前端發(fā)起 post 請求,當(dāng)請求成功被返回執(zhí)行第一個(gè)回調(diào)函數(shù),請求沒有被成功返回則執(zhí)行第二個(gè)回調(diào)函數(shù)。
// 新建文章
// 即將被儲(chǔ)存的數(shù)據(jù) 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: '發(fā)表文章成功',
type: 'success'
})
// 保存成功后跳轉(zhuǎn)至文章列表頁
self.refreshArticleList()
},
response => console.log(response)
)
后端存儲(chǔ)數(shù)據(jù)并返回結(jié)果
// 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 構(gòu)建了一個(gè)簡單的服務(wù)器,幾乎只用于操作數(shù)據(jù)庫。
app.js 位于項(xiàng)目根目錄,使用 node app 運(yùn)行服務(wù)器。
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')
})
給自己挖了一個(gè)坑。因?yàn)榈卿浿笮枰4嬗脩魻顟B(tài),用來判斷用戶是否登錄,如果登錄則可以進(jìn)入后臺(tái)管理,如果沒有登錄則不能進(jìn)入后臺(tái)管理頁面。之前寫 node 的時(shí)候用的是 session 來保存,不過spa應(yīng)用不同于前后端不分離的應(yīng)用,我在前端對用戶輸入的賬號(hào)密碼進(jìn)行了判斷,如果成功則請求登錄在后端保存 session。不過不知道出于什么原因,session 總是沒辦法賦值。因?yàn)槲?node 學(xué)的也是半吊子,所以暫時(shí)放著,等我搞清楚了再來填坑。
收獲
1.學(xué)一個(gè)新模塊,新框架第一步就是閱讀官方文檔。
2.不要覺得讀文檔費(fèi)時(shí)間,認(rèn)真的讀一遍官方文檔比你瞎折騰來得有效率。
3.閱讀與你項(xiàng)目相關(guān)的優(yōu)秀項(xiàng)目的源碼,學(xué)習(xí)別人如何組織代碼。
4.自己的解決方案不一定是最優(yōu)解,不過在找到最優(yōu)解之前不妨自己先試試。
5.框架模塊的使用都不難,套API的活每個(gè)人都能干,只是快與慢的差別。
6.嘗試思考這個(gè)API是如何實(shí)現(xiàn)的。
7.了解了完整的web應(yīng)用是如何運(yùn)作的,包括服務(wù)器,數(shù)據(jù)庫,前端是如何聯(lián)系在一起的。
源碼:可以點(diǎn)擊這里或者本地下載
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Vue3+Koa2實(shí)現(xiàn)圖片上傳功能的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何使用Vue3和Koa2實(shí)現(xiàn)圖片上傳功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-02-02
vue項(xiàng)目中使用AvueJs的詳細(xì)教程
Avue.js是基于現(xiàn)有的element-ui庫進(jìn)行的二次封裝,簡化一些繁瑣的操作,核心理念為數(shù)據(jù)驅(qū)動(dòng)視圖,主要的組件庫針對table表格和form表單場景,這篇文章給大家介紹了vue項(xiàng)目中使用AvueJs的相關(guān)知識(shí),感興趣的朋友跟隨小編一起看看吧2022-10-10
Vue使用自定義指令實(shí)現(xiàn)頁面底部加水印
本文主要實(shí)現(xiàn)給項(xiàng)目的整個(gè)背景加上自定義水印,可以改變水印的文案和字體顏色等,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06
Vue預(yù)渲染:prerender-spa-plugin生成靜態(tài)HTML與vue-meta-info更新meta
Vue.js中,prerender-spa-plugin和vue-meta-info插件的結(jié)合使用,提供了解決SEO問題的方案,prerender-spa-plugin通過預(yù)渲染技術(shù)生成靜態(tài)HTML,而vue-meta-info則能動(dòng)態(tài)管理頁面元數(shù)據(jù),本文將探討如何使用這兩個(gè)工具優(yōu)化Vue.js項(xiàng)目的SEO表現(xiàn),包括安裝、配置及注意事項(xiàng)2024-10-10
vue2.x中h函數(shù)(createElement)與vue3中的h函數(shù)詳解
h函數(shù)本質(zhì)就是createElement(),h函數(shù)其實(shí)是createVNode的語法糖,返回的就是一個(gè)Js普通對象,下面這篇文章主要給大家介紹了關(guān)于vue2.x中h函數(shù)(createElement)與vue3中h函數(shù)的相關(guān)資料,需要的朋友可以參考下2022-12-12
Vue開發(fā)實(shí)現(xiàn)滑動(dòng)驗(yàn)證組件
這篇文章主要為大家詳細(xì)介紹了如何利用Vue開發(fā)實(shí)現(xiàn)簡單的滑動(dòng)驗(yàn)證組件,并且適配移動(dòng)和PC,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-07-07

