首页 文章资讯内容详情

一个 Vue + Node + MongoDB 博客系统

2026-06-01 4 花语

本文内容纲要:

-源码 -实现的功能 -使用到的技术 -前端 -后端 -基本思路 -项目目录 -webpack配置 -前端部分 -命名视图 -router -elementUI -vue-resource -后端部分 -收获

源码

耗时半载(半个月)的大项目终于完成了。这是一个博客系统,使用Vue做前端框架,Node+express做后端,数据库使用的是MongoDB。实现了用户注册、用户登录、博客管理(文章的修改和删除)、文章编辑(Markdown)、标签分类等功能。

很早之前就想写一个个人博客。学了Vue之后,把前端部分写出来,然后Node一直拖拖拉拉的学了很久,中间又跑去实习了一段时间,所以直到回学校之后才列了个计划把这个项目实现了。

翻出之前写的前端部分,好丑啊,干脆推掉重写吧。前端模仿的是hexo的经典主题NexT,本来是想把源码直接拿过来用的,后来发现还不如自己写来得快,就全部自己动手实现成vuecomponents。

实现的功能

文章的编辑,修改,删除 支持使用Markdown编辑与实时预览 支持代码高亮 给文章添加标签 支持用户注册登录

使用到的技术

前端

Vue.js vue-cli vue-router vue-resource element-ui marked highlight.js

后端

Node.js Express Mongoose

基本思路

前端使用vue-router操作路由,实现单页应用的效果。使用vue-resource从后台获取数据,数据的处理全部都在前端,所以后端要做的事情很简单——把前端打包好的数据存进数据库中和从数据库中取出数据。前后端使用统一的路由命名规则。

项目目录

|app.js后端入口 |index.html入口页面 |.babelrcbabel配置 |.gitignoregit配置 |package.json |webpack.config.jswebpack配置 | |-distvue打包生成的文件 | |-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。

然后打开后端服务器nodeapp,后端监听3000端口。

最后打开前端开发模式npmrundev,前端启动了一个webpack服务器,监听8080端口用于热刷新。通过配置把前端的http请求转到3000端口。

前端部分

命名视图

所有页面都用到的元素可以写在App.vue上面,也可以写成公共组件。我在App.vue中使用了命名视图,因为sidebar这个组件有的页面需要有的不需要,不需要的时候就不用加载。

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

router

路由的配置写在main.js中,分为前台展示和后台管理。后台管理统一以‘/admin’开头。注册页和登录页写在一起了,上面有两个按钮“注册”和“登录”(我好懒-_-)。

//main.js constrouter=newVueRouter({ 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} ] })

elementUI

使用了element用于消息提醒和标签分类。并不需要整个引入,而是使用按需引入。

//main.js //按需引用element import{Button,Message,MessageBox,Notification,Popover,Tag,Input}fromelement-ui importelement-ui/lib/theme-default/index.css constcomponents=[Button,Message,MessageBox,Notification,Popover,Tag,Input] components.forEach((item)=>{ Vue.component(item.name,item) }) constMsgBox=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=>{ //successcallback },response=>{ //errorcallback }); 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 letobj={ 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){ newdb.Article(req.body.articleInformation).save(function(err){ if(err){ res.status(500).send() return } res.send() }) })

后端部分

后端使用express构建了一个简单的服务器,几乎只用于操作数据库。

app.js位于项目根目录,使用nodeapp运行服务器。

constexpress=require(express) constfs=require(fs) constpath=require(path) constbodyParse=require(body-parser) constsession=require(express-session) constMongoStore=require(connect-mongo)(session) constrouter=require(./server/router) constapp=express() constresolve=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(trustproxy,1)//trustfirstproxy app.use(session({ secret:blog, resave:false, saveUninitialized:true, cookie:{ secure:true, maxAge:2592000000 }, store:newMongoStore({ url:mongodb://localhost:27017/blog }) })) app.get(*,function(req,res){ lethtml=fs.readFileSync(resolve(./+index.html),utf-8) res.send(html) }) app.listen(3000,function(){ console.log(访问地址为localhost:3000) })

给自己挖了一个坑。因为登录之后需要保存用户状态,用来判断用户是否登录,如果登录则可以进入后台管理,如果没有登录则不能进入后台管理页面。之前写node的时候用的是session来保存,不过spa应用不同于前后端不分离的应用,我在前端对用户输入的账号密码进行了判断,如果成功则请求登录在后端保存session。不过不知道出于什么原因,session总是没办法赋值。因为我node学的也是半吊子,所以暂时放着,等我搞清楚了再来填坑。

收获

学一个新模块,新框架第一步就是阅读官方文档。 不要觉得读文档费时间,认真的读一遍官方文档比你瞎折腾来得有效率。 阅读与你项目相关的优秀项目的源码,学习别人如何组织代码。 自己的解决方案不一定是最优解,不过在找到最优解之前不妨自己先试试。 框架模块的使用都不难,套API的活每个人都能干,只是快与慢的差别。 尝试思考这个API是如何实现的。 了解了完整的web应用是如何运作的,包括服务器,数据库,前端是如何联系在一起的。

本文内容总结:源码,实现的功能,使用到的技术,前端,后端,基本思路,项目目录,webpack配置,前端部分,命名视图,router,elementUI,vue-resource,后端部分,收获,

原文链接:https://www.cnblogs.com/chaohangz/p/6748918.html