前言笔者前端开发打交道有一段时间了,一直保留着最初对node的恐惧。一个属于自己的视觉新视野,希望正在看这篇文章的你可以和我一起尝试一下。不耐烦的我再提供一波传送门github:https://github.com/tenggouwa/...可以先star,再拉代码,慢慢看这篇文章。KOAnextgenerationwebframeworkfornode.js是node.js的下一代web框架。由快递团队打造,特点:优雅、简洁、灵活、体积小。几乎所有的功能都需要通过中间件来实现。环境搭建nodenode官方下载地址:https://nodejs.org/zh-cn/down...mongodbmac下mongodb安装教程:https://www.jianshu.com/p/724...windows下mongodb安装教程:https://blog.csdn.net/zhongka...robomongo(mongodb数据库可视化-免费):https://robomongo.org/download在本地安装nodemonnodemon会监控你的代码,当有变化时自动帮助你重启项目(好东西)npm:https://www.npmjs.com/package...yarn(optional)---而不是npm/cnpmhomebrew(optional)---包版本管理工具HelloWorld!!!Createdirectorymkdirnode-app&&cdnode-appnpminityarnaddkoa-Stouchapp.js在编辑器中打开app.js,输入以下代码constKoa=require('koa');constapp=newKoa();app.use(asyncctx=>{//ctx.body是服务端的响应数据awaitctx.body='Helloworld!!!';})//监听端口,启动程序app.listen(3000,err=>{if(err)throwerr;console.log('runingat3000');})启动app.jsnodeapp或nodemonapplocalaccesslocalhost:3000gotit!!!!KoaRouterinstallkoa-routeryarnaddkoa-router-在skoa-app目录新建controller文件,在controller下新建home.js,在skoa-app目录新建router.js,输入以下代码在控制器文件中,constrouter=require('koa-router')()module.exports=(app)=>{router.get('/index',app.controller.home.index)}home.js输入以下代码module.exports={index:async(ctx,next)=>{console.log(ctx)//输出ctx查看内容ctx.response.body='
HOMEpageindex
'},}运行代码nodeapp或nodemonapp本地访问localhost:3000/index搞定了!!!!processpostkoa-bodyparserInstallkoa-bodyparseryarnaddkoa-bodyparser-Srouter.js添加代码router.post('/post',bodyParser(),app.controller.home.post)//关注后面的bodyParser()home.js'post'添加代码post:async(ctx,next)=>{console.log(ctx.request.body)//输出ctx查看内容},使用postman创建post请求,访问localhost:3000/post,并传递参数,看终端返回的内容就搞定了!!!处理跨域koa2-cors安装yarnaddkoa2-cors-S在app.js中添加如下代码constcors=require('koa2-cors').........//其他代码app.use(cors())至此,我们有了一套简单的koa项目,可以前后台交互,也可以用mock数据搭建mongodb。在环境搭建中,可以看到项目中安装mongodb和数据库可视化的方法在yarnaddmongoose-S中,创建一个models文件夹,在app.js中添加如下代码constmongoose=require('mongoose')constpath=require('path')constfs=require('fs')//链接数据库必须放在koa前面mongoose.Promise=require('bluebird')mongoose.connect('mongodb://127.0.0.1/tenggouwa',{useNewUrlParser:true})//获取js对象所在路径对应数据库表所在constmodels_path=path.join(__dirname,'./models')//递归形式,读取models文件夹下的js模型文件,并requirevarwalk=function(modelPath){fs.readdirSync(modelPath).forEach(function(file){varfilePath=path.join(modelPath,'/'+file)varstat=fs.statSync(filePath)if(stat.isFile()){if(/(.*)\.(js|coffee)/.test(file)){require(filePath)}}elseif(stat.isDirectory()){walk(filePath)}})}walk(models_path)这一步可以链接工程mongodbinmodels创建block.js,添加如下代码'usestrict'varmongoose=require('mongoose')varSchema=mongoose.Schema;/***定义一个schema(相当于传统的表结构)*每个schemamapsmongoDB的一个集合*定义了(只是定义,不实现)这个集合中文档的结构,就是定义文档有哪些字段,字段类型是什么,字段的默认值是什么等.*除了定义结构体,还定义了文档的实例方法、静态模型方法、复合索引、中间件等*/varBlockSchema=newSchema({peers:String,blocks:String,createAt:{type:Date,default:Date.now()},updateAt:{type:Date,dafault:Date.now()}})/***定义模型*模型用来实现我们定义的模式,调用mongoose.model编译Schema得到Model*@type{[type]}*///参数User数据库中的集合名,如果不存在则创建.//console.log(BlockSchema)varBlock=mongoose.model('Block',BlockSchema)module.exports=Block```这一步是添加传统意义上的表结构,放到Block表中。然后我们就可以在controller中操作mongodb,进行业务操作了。例如:delBlock:async(ctx,next)=>{constparams=ctx.request.body//获取返回的参数constresult=awaitBlock.where({//通过id_id查找Block中对应的数据:params.id}).remove()//删除这条数据},明白了!!!mongodb常用操作savedatasave()retrievedataqueryfind()finOne()where()changedatawhere().update()删除数据where().remove()sortfind().sort()pagingfind().sort().skip(pagenumber).limit(singlepagedata)搞定了!!!JustDoIt写的in最后,当你看到这篇文章的时候,你已经了解了koa+mongdb的基本用法。希望大家通过学习node及其生态来提升自己的知识储备,跟我来吧!