当前位置: 首页 > 后端技术 > Node.js

记得React+Koa+Mysql搭建个人博客

时间:2023-04-03 23:13:05 Node.js

前言由于一直使用vue写业务,为了熟悉react的开发模式,所以选择了react。数据库一开始用的是mongodb,后来换成了mysql。一套下来感觉mysql也很好用。react-router、koa、mysql都是从0开始接触开发的,期间遇到了很多问题。印象最深的是react-router是参考官方文档配置的。它无法运行。花了好几个小时。发现我看的文档是v1.0,但是工程是v4.3。好在参考资料多了,问题也就迎刃而解了。博客介绍通过create-react-app构建前端工程,通过koa-generator将server端前后端分离。博客页面和后台管理都在blog-admin中,包含/admin的路由登录拦截。前端:react+antd+react-router4+axios服务器端:koa2+mysql+sequelize部署:服务器端运行在3000端口,前端80端口,nginx设置代理预览地址web端源码server端源码likesor帮到你了,欢迎star功能[x]登录[x]分页[x]查询[x]标签列表[x]分类列表[x]收藏列表[x]文章列表[x]发表文章时间线[x]文章访问统计[x]返回顶部[x]]适配移动端的博客[]适配移动端的后台[]文章访问量可视化[]发表??评论[]渲染优化、打包优化效果标签分类收藏文章编辑博客页面响应式运行项目前端gitclonehttps://github.com/gzwgq222/blog-admin.gitcdblog-adminnpminstalllocalhost:2019server端本地安装mysql,新建dev数据库gitclonehttps://github.com/gzwgq222/blog-server.gitcdblog-servernpminstallserver-side前端react+antd的开发比较顺利,这里就不赘述了。主要记录koa+mysql相关事宜。安装koa-generatornpminstall-gkoa-generato以创建节点服务器项目。koanode-server安装依赖cdnode-servernpninstall运行npmdev。你好Koa2!表示操作成功。先看路由文件index.jsconstrouter=require('koa-router')()router.get('/',async(ctx,next)=>{awaitctx.render('index',{title:'HelloKoa2!'})})router.get('/string',async(ctx,next)=>{ctx.body='koa2string'})router.get('/json',async(ctx,next)=>{ctx.body={title:'koa2json'}})module.exports=routerusers.jsconstrouter=require('koa-router')()router.prefix('/users')router.get('/',function(ctx,next){ctx.body='这是用户响应!'})router.get('/bar',function(ctx,next){ctx.body='this是一个users/barresponse'})module.exports=router分别访问下面的路由localhost:3000/stringlocalhost:3000/userslocalhost:3000/bar你可能猜到了,koa-router在定义路由访问时返回了相应的内容,那么我们只需要把相应的数据返回即可,但是我们的数据还得从数据库中查询出来。本地安装mysql项目安装mysqlnpminstallmysql--save项目安装sequelizesequelize是一个ORM节点框架,封装了SQL查询语句,方便我们使用OOP操作数据库npminstall--savesequelize新建一个sequelize.js并建立一个连接池constSequelize=require('sequelize');constsequelize=newSequelize('dev','root','123456',{host:'localhost',dialect:'mysql',operatorsAliases:false,pool:{max:5,min:0,acquire:30000,idle:10000}})sequelize.authenticate().then(()=>{console.log('MYSQL连接成功...');}).catch(err=>{console.error('链接失败:',err);});//根据模型自动创建表sequelize.sync()module.exports=sequelizecreatesmodel,controllers文件夹定义model:definetablestructure;controller:定义数据库的查询方法。以tag.js为例model=>tag.jsconstsequelize=require('../sequelize')constSequelize=require('sequelize')constmoment=require('moment')//日期处理库//定义表结构consttag=sequelize.define('tag',{id:{type:Sequelize.INTEGER(11),//设置字段类型primaryKey:true,//设置为主构建autoIncrement:true//自增},name:{type:Sequelize.STRING,unique:{//Uniquemsg:'Added'}},createdAt:{type:Sequelize.DATE,defaultValue:Sequelize.NOW,get(){//this.getDataValue获取当前字段值返回moment(this.getDataValue('createdAt')).format('YYYY-MM-DDHH:mm')}},updatedAt:{type:Sequelize.DATE,defaultValue:Sequelize.NOW,get(){returnmoment(this.getDataValue('updatedAt')).format('YYYY-MM-DDHH:mm')}}},{//sequelize会自动使用传入的模型名称(define的第一个参数)的复数number作为表名,设置true取消默认设置freezeTableName:true})module.exports=tagcontroller=>tag.s定义create,findAll,findAndCountAll,destroy方法constTag=require('../model/标签')constOp=require('sequelize').OpconstlistAll=async(ctx)=>{constdata=await标签。findAll()ctx.body={code:1000,data}}constlist=async(ctx)=>{constquery=ctx.queryconstwhere={name:{[Op.like]:`%${query.name}%`}}const{行:数据,计数:total}=awaitTag.findAndCountAll({where,offset:(+query.pageNo-1)*+query.pageSize,limit:+query.pageSize,order:[['createdAt','DESC']]})ctx.body={data,total,code:1000,desc:'success'}}constcreate=async(ctx)=>{constparams=ctx.request.bodyif(!params.name){ctx.body={code:1003,desc:'Tagcannotbeempty'}returnfalse}try{awaitTag.create(params)ctx.body={code:1000,data:'创建成功'}}catch(err){constmsg=err.errors[0]ctx.body={代码:300,数据:msg.value+msg.message}}}constdestroy=asyncctx=>{awaitTag.destroy({where:ctx.request.body})ctx.body={code:1000,desc:'删除成功'}}module.exports={list,create,listAll,destroy在routers文件夹index.js中引入定义的tagcontroller,定义路由constrouter=require('koa-router')()constTag=require('../controllers/tag')//tagrouter.get('/tag/list',Tag.list)router.get('/tag/list/all',Tag.listAll)router.post('/tag/create',Tag.create)router.post('/tag/destroy',Tag.destroy)module.exports=router/*如果每条路由都是单独的文件,可以使用router.prefix定义路由前缀router.prefix('/tag')router.get('/list',Tag.list)router.get('/list/all',Tag.listAll)router.post('/create',Tag.create)router.post('/destroy',Tag.destroy)*/因为app在里面引入了索引路由器。js调用app.use,这里就不用介绍了。在浏览器中输入localhost:3000/tag/list可以看到返回的数据结构,但是数据是一个空数组,因为我们这里还没有添加任何数据,model定义表结构,sequelize操作数据库,以及koa-router定义了路由过程。其他表结构和接口定义同理。总结之前没有写过nodeserver和react。零搭建这个博客,踩了一些坑,学到了很多,比如react开发模式,react-router,sequelize操作mysqlcrud,koa,nginx配置等等,麻雀虽小,但也是一个完整的前端和后端开发经验。脱离浏览器的限制,喜欢海贼王,打开了新世界的大门,求海贼王。。。web端源码,服务端源码,详细服务端使用说明,会补上一篇关于这个部署在个人博客。链接reactreact-router4antdreact-draft-wysiwygkoa2sequelize初尝react+Node,错误之处还望指正,欢迎提issue