Koa2RESTfulAPI服务器脚手架
这是一个基于Koa2的轻量级RESTfulAPIServer脚手架,支持ES6。
约定使用JSON格式传输数据,POST、PUT、DELET方法支持的Cotet-Type为 applicatio/x-www-form-urlecoded、multipart/form-data、applicatio/jso可配置支持跨域。非上传文件推荐applicatio/x-www-form-urlecoded。通常情况下返回applicatio/jso格式的JSON数据。
可选用Mogodb、Redis非关系型数据库和PostgreSQL、 MySQL、MariaDB、SQLite、MSSQL关系型数据库,考虑RESTfulAPIServer的实际开发需要,这里通过sequelize.js作为ORM,同时提通过Promise执行SQL直接操作Mysql数据库的方法(不管什么方法,注意安全哦)。
此脚手架只安装了一些和Koa2不冲突的搭建RESTfulAPIServer的必要插件,附带每一个插件的说明。采用ESlit进行语法检查。
因此脚手架主要提供RESTfulAPI,故暂时不考虑前端静态资源处理,只提供静态资源访问的基本方法便于访问用户上传到服务器的图片等资源。基本目录结构与vue-cli保持一致,可配合React、AgularJS、Vue.js等前端框架使用。在Cordova/PhoeGap中使用时需要开启跨域功能。
免责声明: 此脚手架仅为方便开发提供基础环境,任何人或组织均可随意克隆使用,使用引入的框架需遵循原作者规定的相关协议(框架列表及来源地址在下方)。采用此脚手架产生的任何后果请自行承担,本人不对此脚手架负任何法律责任,使用即代表同意此条。
目前暂未加入软件测试模块,下一个版本会加入该功能并提供集成方案。
Chia大陆用户请自行优化网络。
开发使用说明$ git cloe https://github.com/yi-ge/koa2-API-scaffold.git$ cd mv koa2-API-scaffold$ pm istall$ pm ru dev # 可执行pm start跳过ESlit检查。访问: https://127.0.0.1:3000/
调试说明$ pm ru dev --debugOr$ pm start --debug支持Node.js原生调试功能:https://odejs.org/api/debugger.html
开发环境部署生成ode直接可以执行的代码到dist目录:
$ pm ru build$ pm ru productio # 生产模式运行Or$ ode dist/app.jsPM2部署说明提供了PM2部署RESTfulAPIServer的示例配置,位于“pm2.js”文件中。
$ pm2 start pm2.jsPM2配合Docker部署说明: https://pm2.keymetrics.io/docs/usage/docker-pm2-odejs/
Docker部署说明$ docker pull ode$ docker ru -itd --ame RESTfulAPI -v `pwd`:/usr/src/app -w /usr/src/app ode ode ./dist/app.js通过'dockerps'查看是否运行成功及运行状态
Liux/Mac直接后台运行生产环境代码有时候为了简单,我们也这样做:
$ ohup ode ./dist/app.js > logs/out.log &查看运行状态(如果有'odeapp.js'出现则说明正在后台运行):
$ ps aux|grep app.js查看运行日志
$ cat logs/out.log监控运行状态
$ tail -f logs/out.log配合Vue-cli部署说明Vue-cli(Vue2)运行'pmrubuild'后会在'dist'目录中生成所有静态资源文件。推荐使用Ngix处理静态资源以达最佳利用效果,然后通过上述任意一种方法部署RESTfulAPI服务器。前后端是完全分离的,请注意Koa2RESTfulAPIServer项目中cofig/mai.jso里面的跨域配置。
推荐的Ngix配置文件:
server { liste 80; liste [::]:80; server_ame abc.com www.abc.com; #绑定域名 idex idex.html idex.htm; root /www/app/dist; #Vue-cli编译后的dist目录 locatio ~ .*\.(gif|jpg|jpeg|pg|bmp|swf)$ { expires 30d; } locatio ~ .*\.(js|css)?$ { expires 12h; } locatio ~ /\. { dey all; } access_log off; #访问日志路径 }Docker中Ngix运行命令(将上述配置文件任意命名放置于gix_cofig目录中即可):
$ docker ru -itd -p 80:80 -p 443:443 -v `pwd`/gix_cofig:/etc/gix/cof.d gix引入插件介绍引入插件的版本将会持续更新
引入的插件:koa@2koa-body@2koa-router@extkoa-sessio2koa-static2koa-composerequire-directorybabel-clibabel-registerbabel-plugi-trasform-rutimebabel-preset-es2015babel-preset-stage-2gulpgulp-eslitesliteslit-cofig-stadardeslit-friedly-formattereslit-plugi-htmleslit-plugi-promiseodemailerpromise-mysql
目录结构说明.├── README.md├── .babelrc # Babel 配置文件├── .editorcofig # 编辑器风格定义文件├── .eslitigore # ESlit 忽略文件列表├── .eslitrc.js # ESlit 配置文件├── .gitigore # Git 忽略文件列表├── gulpfile.js # Gulp配置文件├── package.jso # 描述文件├── pm2.js # pm2 部署示例文件├── build # build 入口目录│ └── dev-server.js # 开发环境 Babel 实时编译入口├── src # 源代码目录,编译后目标源代码位于 dist 目录│ ├── app.js # 入口文件│ ├── cofig.js # 主配置文件(*谨防泄密!)│ ├── plugi # 插件目录│ └── smtp_sedemail # 示例插件 - 发邮件│ ├── tool # 工具目录│ ├── PlugiLoader.js # 插件引入工具│ └── Commo.js # 示例插件 - 发邮件│ ├── lib # 库目录│ ├── cotrollers # 控制器│ ├── models # 模型│ ├── routes # 路由│ └── services # 服务├── assets # 静态资源目录└── logs # 日志目录各类主流框架调用RESTfulAPI的示例代码(仅供参考)AgularJS(Ioic同)$http({ method: 'post', url: 'https://localhost:3000/xxx', data: {para1:'para1',para2:'para2'}, headers: { 'Cotet-Type': 'applicatio/x-www-form-urlecoded' } }).success(fuctio (data) { }).error(fuctio (data) { })jQuery$.ajax({ cache: false, type: 'POST', url: 'https://localhost:3000/xxx', data: { para1: para1 }, asyc: false, dataType: 'jso', success: fuctio (result) { }, error: fuctio (err) { cosole.log(err) }})// 上传文件//创建FormData对象var data = ew FormData()//为FormData对象添加数据//$.each($('#iputfile')[0].files, fuctio (i, file) { data.apped('upload_file', file)})$.ajax({ url: 'https://127.0.0.1:3000/api/upload_oss_img_demo', type: 'POST', data: data, cache: false, cotetType: false, //不可缺 processData: false, //不可缺 success: fuctio (data) { cosole.log(data) if (data.result == 'ok') { $('#zzzz').attr('src', data.img_url) } }})MUImui.ajax({ url: 'https://localhost:3000/xxx', dataType: 'jso', success: fuctio(data){ }, error: fuctio(data){ cosole.log('error!') }})JavaScript var xhr = ew XMLHttpRequest() xhr.ope('POST', 'https://localhost:3000/xxx', true) //POST或GET,true(异步)或 false(同步) xhr.setRequestHeader('Cotet-type', 'applicatio/x-www-form-urlecoded') xhr.withCredetials = true xhr.oreadystatechage = fuctio () { if (obj.readyState == 4 && obj.status == 200 || obj.status == 304) { var gotServices = JSON.parse(xhr.resposeText) }else{ cosole.log('ajax失败了') } } xhr.sed({para1: para1})vue-resourcehttps://github.com/pagekit/vue-resource
// global Vue objectVue.http.post('/someUrl', [body], { headers: {'Cotet-type', 'applicatio/x-www-form-urlecoded'}}).the(successCallback, errorCallback)fetchhttps://github.com/github/fetch
fetch('/users', { method: 'POST', headers: { 'Cotet-Type': 'applicatio/jso' }, body: JSON.strigify({ ame: 'Hubot', logi: 'hubot', })}).the(fuctio(respose) { // respose.text()}).the(fuctio(body) { // body})// 文件上传var iput = documet.querySelector('iput[type='file']')var data = ew FormData()data.apped('file', iput.files[0])data.apped('user', 'hubot')fetch('/avatars', { method: 'POST', body: data})superagethttps://github.com/visiomedia/superaget
request.post('/user') .set('Cotet-Type', 'applicatio/jso') .sed('{'ame':'tj','pet':'tobi'}') .ed(callback)requesthttps://github.com/request/request
request.post('/api').form({key:'value'}), fuctio(err,httpRespose,body){ /* ... */ })在React中可以将上述任意方法其置于compoetDidMout()中,Vue.js同理。
彻底移除ESlit方法删除package.jso的devDepedecies中所有eslit开头的插件,根目录下的“.eslitigore、.eslitrc.js”文件,并且修改package.jso的dev为:
'dev': 'gulp start'删除gulpfile.js中的lit、eslit_start两个任务,并且把default改为“gulp.task('default',['start']”。
更新说明v0.0.42017年02月07日15:57:171、修改了部分配置文件的配置方法,使之更为规范(老版本用户无须理会,对程序没有影响)。2、修改了eslitrc.js文件中的JavaScript版本配置,改为ES8,兼容asyc、await。3、修改gulpfile.js文件第12行,检查src/**/*.js文件。
评论