您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)怎么利用Vue.js+Node.js+MongoDB實(shí)現(xiàn)一個博客系統(tǒng),小編覺得挺實(shí)用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
go是golang的簡稱,golang 是Google開發(fā)的一種靜態(tài)強(qiáng)類型、編譯型、并發(fā)型,并具有垃圾回收功能的編程語言,其語法與 C語言相近,但并不包括如枚舉、異常處理、繼承、泛型、斷言、虛函數(shù)等功能。
前言
這篇文章實(shí)現(xiàn)的博客系統(tǒng)使用 Vue 做前端框架,Node + express 做后端,數(shù)據(jù)庫使用的是 MongoDB。實(shí)現(xiàn)了用戶注冊、用戶登錄、博客管理(文章的修改和刪除)、文章編輯(Markdown)、標(biāo)簽分類等功能。
前端模仿的是 hexo 的經(jīng)典主題 NexT ,本來是想把源碼直接拿過來用的,后來發(fā)現(xiàn)還不如自己寫來得快,就全部自己動手實(shí)現(xiàn)成 vue components。
實(shí)現(xiàn)的功能
1.文章的編輯,修改,刪除
2.支持使用 Markdown 編輯與實(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 從后臺獲取數(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 自動生成的,添加了讓前后端http請求都轉(zhuǎn)到node的3000端口,而不是前端的8080端口的配置。
devServer: { historyApiFallback: true, noInfo: true, //讓前后端http請求都轉(zhuǎn)到node的3000端口,而不是前端的8080端口 proxy: { '/': { target: 'http://localhost:3000/' } } }
這里涉及一個新手可能會不明白的問題(我之前就搗鼓了半天)。
開發(fā)的時候要先打開數(shù)據(jù)庫 MongoDB ,使用命令 mongod。
然后打開后端服務(wù)器 node app,后端監(jiān)聽 3000 端口。
最后打開前端開發(fā)模式 npm run dev,前端啟動了一個 webpack 服務(wù)器,監(jiān)聽 8080 端口用于熱刷新。通過配置把前端的http請求轉(zhuǎn)到 3000 端口。
前端部分
命名視圖
所有頁面都用到的元素可以寫在 App.vue 上面,也可以寫成公共組件。我在 App.vue 中使用了命名視圖,因?yàn)?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 中,分為前臺展示和后臺管理。后臺管理統(tǒng)一以 ‘/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 用于消息提醒和標(biāo)簽分類。并不需要整個引入,而是使用按需引入。
// 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í)行第一個回調(diào)函數(shù),請求沒有被成功返回則執(zhí)行第二個回調(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í)行第一個回調(diào)函數(shù),請求沒有被成功返回則執(zhí)行第二個回調(diào)函數(shù)。
// 新建文章 // 即將被儲存的數(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) )
后端存儲數(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)建了一個簡單的服務(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') })
給自己挖了一個坑。因?yàn)榈卿浿笮枰4嬗脩魻顟B(tài),用來判斷用戶是否登錄,如果登錄則可以進(jìn)入后臺管理,如果沒有登錄則不能進(jìn)入后臺管理頁面。之前寫 node 的時候用的是 session 來保存,不過spa應(yīng)用不同于前后端不分離的應(yīng)用,我在前端對用戶輸入的賬號密碼進(jìn)行了判斷,如果成功則請求登錄在后端保存 session。不過不知道出于什么原因,session 總是沒辦法賦值。因?yàn)槲?node 學(xué)的也是半吊子,所以暫時放著,等我搞清楚了再來填坑。
收獲
1.學(xué)一個新模塊,新框架第一步就是閱讀官方文檔。
2.不要覺得讀文檔費(fèi)時間,認(rèn)真的讀一遍官方文檔比你瞎折騰來得有效率。
3.閱讀與你項(xiàng)目相關(guān)的優(yōu)秀項(xiàng)目的源碼,學(xué)習(xí)別人如何組織代碼。
4.自己的解決方案不一定是最優(yōu)解,不過在找到最優(yōu)解之前不妨自己先試試。
5.框架模塊的使用都不難,套API的活每個人都能干,只是快與慢的差別。
6.嘗試思考這個API是如何實(shí)現(xiàn)的。
7.了解了完整的web應(yīng)用是如何運(yùn)作的,包括服務(wù)器,數(shù)據(jù)庫,前端是如何聯(lián)系在一起的。
關(guān)于“怎么利用Vue.js+Node.js+MongoDB實(shí)現(xiàn)一個博客系統(tǒng)”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。