node框架koa
node的两大常见web服务器框架有express和koa,之前已经介绍过express了现在来介绍下koa吧~
koa也是express团队的出品,意在利用es7新出的async来告别“回调地狱”
下面来看看koa的大概用法:
const koa = require('koa') //koa路由器,不同于express天生自带路由,koa需要引入路由中间件 const koaRouter = require('koa-router') //koa的静态文件处理中间件 const static = require('koa-static') //处理post过来文件的中间件 const body = require('koa-better-body'); //配合better-body使用 const convert = require('koa-convert'); // url解析 const url = require('url') //不同于express,koa需要new const server = new koa() //监听端口 server.listen(8080) //配置接受文件存储位置,扩展名是否加上 server.use(convert(body({ uploadDir: './upload', keepExtensions: true }))) //正常koa的使用方法use server.use(async (ctx,next) => { ctx.user_id = '123456789' //跨域可能需要加上的2个http头 ctx.set('Access-Control-Allow-Origin','*') ctx.set('Access-Control-Allow-Headers','*') await next() }) //路由需要new const r1 = new koaRouter() //嵌套路由 r1.use('/test', async ctx => { //获取http头信息,例如x-token是自定义的http头 let token = ctx.headers['x-token'] }) r1.use('/api', require('./routers/api.routers')) //返回给koa server的时候需要调用routes函数 server.use(r1.routes()) //koa静态文件中间件 server.use(static('./www'))
'./routers/api.routers.js'/:
const koaRouter = require('koa-router') const db = require('../libs/mysql') const r1 = new koaRouter() //操作日志 r1.get('/collect/:type/:data', async ctx => { // ctx.params获取url上的顶死的参数 let {type,data} = ctx.params // ctx.query获取?后的参数 let {username, password} = ctx.query await db.insert('collect_table', { type, data }) ctx.body = {OK: true} }) //获取餐厅 r1.post('/restaurant/:page/:size', async ctx => { //获取post body上的参数 console.log(this.request.body) // if buffer or text console.log(this.request.files) // if multipart or urlencoded console.log(this.request.fields) // if json // ------------------------------------------------------------------------- let {page,size} = ctx.params let data = await db.query(` SELECT * FROM restaurant_table LIMIT ${page*size},${size} `) ctx.body = data }) //嵌套路由需要返回routes() module.exports = r1.routes()
'../libs/mysql.js'
const mysql = require('mysql') const config = require('../config') const assert = require('assert') const db = mysql.createPool({ host:config.DB_HOST, port:config.DB_PORT, database:config.DB_DATABASE, user:config.DB_USER, password:config.DB_PASS }) function filter(val) { return val.replace(/"/g,'\\"').replace(/'/g,'\\\'') } db._query = db.query db.query = function(sql) { return new Promise((resolve, reject) => { db._query(sql, (err, data) => { if(err) { reject(err) } else { resolve(data) } }) }) } db.select = function(table, fields, data) { let WHERE = '' if(!data) { WHERE = '1 = 1' } else { let arr = []; for(let key in data){ arr.push(`${key}="${filter(data[key])}"`) } WHERE = arr.join(' AND ') } return db.query(`SELECT ${fields} FROM ${table} WHERE ${WHERE}`) } db.insert = function(table, data) { let keys = [] let vals = [] for(let key in data) { keys.push(key) vals.push('"'+filter(data[key].toString())+'"') } return db.query(`INSERT INTO ${table} (${keys.join(',')}) VALUES(${vals.join(',')})`) } db.update = function(table, data, where) { assert(where) assert(typeof where == 'object') let arr = [] for(let i in data) { arr.push(`${i}="${data[i]}"`) } let whereArr = [] for(let i in where) { whereArr.push(`${i}="${where[i]}"`) } return db.query(`UPDATE ${table} SET ${arr.join(',')} WHERE ${whereArr.join(' AND ')}`) } db.delete = function(table, data) { assert(data) assert(typeof data == 'object') let arr = [] for(let i in data) { arr.push(`${i}="${data[i]}"`) } return db.query(`DELETE FROM ${table} WHERE ${arr.join(' AND ')}`) } module.exports = db
显而易见,mysql封装好给koa用只不过是将原来回调的形式换成Promise的形式