常用模块
const Koa = require('koa')const fs = require('fs')const app = new Koa()const Router = require('koa-router')let home = new Router()// 子路由1home.get('/', async ( ctx )=>{ let html = ` <ul> <li><a href="/page/helloworld">/page/helloworld</a></li> <li><a href="/page/404">/page/404</a></li> </ul> ` ctx.body = html})// 子路由2let page = new Router()page.get('/404', async ( ctx )=>{ ctx.body = '404 page!'}).get('/helloworld', async ( ctx )=>{ ctx.body = 'helloworld page!'})// 装载所有子路由let router = new Router()router.use('/', home.routes(), home.allowedMethods())router.use('/page', page.routes(), page.allowedMethods())// 加载路由中间件app.use(router.routes()).use(router.allowedMethods())app.listen(3000, () => { console.log('[demo] route-use-middleware is starting at port 3000')})
- ctx.req VS ctx.request
ctx.request是context经过封装的请求对象,ctx.req是context提供的node.js原生HTTP请求对象,同理ctx.response是context经过封装的响应对象,ctx.res是context提供的node.js原生HTTP请求对象。 - GET 参数获取
1、从上下文中直接获取,ctx.query / ctx.queryString
2、从上下文的request对象中获取,ctx.request.query / ctx.request.queryString - POST 参数获取
使用 koa-bodyparser 中间件
const Koa = require('koa')const app = new Koa()const bodyParser = require('koa-bodyparser')// 使用ctx.body解析中间件app.use(bodyParser())app.use( async ( ctx ) => { if ( ctx.url === '/' && ctx.method === 'POST' ) { // 当POST请求的时候,中间件koa-bodyparser解析POST表单里的数据,并显示出来 let postData = ctx.request.body ctx.body = postData } else { // 其他请求显示404 ctx.body = '<h1>404!!! o(╯□╰)o</h1>' }})app.listen(3000, () => { console.log('[demo] request post is starting at port 3000')})
const Koa = require('koa')const path = require('path')const static = require('koa-static')const app = new Koa()// 静态资源目录对于相对入口文件index.js的路径const staticPath = './static'app.use(static( path.join( __dirname, staticPath)))app.use( async ( ctx ) => { ctx.body = 'hello world'})app.listen(3000, () => { console.log('[demo] static-use-middleware is starting at port 3000')})
- cookie 操作
koa提供了从上下文直接读取、写入cookie的方法
const Koa = require('koa')const app = new Koa()app.use( async ( ctx ) => { if ( ctx.url === '/index' ) { ctx.cookies.set( 'cid', 'hello world', { domain: 'localhost', // 写cookie所在的域名 path: '/index', // 写cookie所在的路径 maxAge: 10 * 60 * 1000, // cookie有效时长 expires: new Date('2017-02-15'), // cookie失效时间 httpOnly: false, // 是否只用于http请求中获取 overwrite: false // 是否允许重写 } ) ctx.body = 'cookie is ok' } else { ctx.body = 'hello world' }})app.listen(3000, () => { console.log('[demo] cookie is starting at port 3000')})
- session 操作
koa2原生功能只提供了cookie的操作,但是没有提供session操作。session就只用自己实现或者通过第三方中间件实现。在koa2中实现session的方案有一下几种:
1、如果session数据量很小,可以直接存在内存中
2、如果session数据量很大,则需要存储介质存放session数据
const Koa = require('koa')const session = require('koa-session-minimal') // 适用于koa2 的session中间件,提供存储介质的读写接口const MysqlSession = require('koa-mysql-session') // 为koa-session-minimal中间件提供MySQL数据库的session数据读写操作const app = new Koa()// 配置存储session信息的mysqllet store = new MysqlSession({ user: 'root', password: 'abc123', database: 'koa_demo', host: '127.0.0.1',})// 存放sessionId的cookie配置let cookie = { maxAge: '', // cookie有效时长 expires: '', // cookie失效时间 path: '', // 写cookie所在的路径 domain: '', // 写cookie所在的域名 httpOnly: '', // 是否只用于http请求中获取 overwrite: '', // 是否允许重写 secure: '', sameSite: '', signed: '',}// 使用session中间件app.use(session({ key: 'SESSION_ID', store: store, cookie: cookie}))app.use( async ( ctx ) => { // 设置session if ( ctx.url === '/set' ) { ctx.session = { user_id: Math.random().toString(36).substr(2), count: 0 } ctx.body = ctx.session } else if ( ctx.url === '/' ) { // 读取session信息 ctx.session.count = ctx.session.count + 1 ctx.body = ctx.session } })app.listen(3000)console.log('[demo] session is starting at port 3000')
# 安装koa模板使用中间件npm install --save koa-views# 安装ejs模板引擎npm install --save ejsconst Koa = require('koa')const views = require('koa-views') const path = require('path')const app = new Koa()// 加载模板引擎app.use(views(path.join(__dirname, './view'), { extension: 'ejs'}))app.use( async ( ctx ) => { let title = 'hello koa2' await ctx.render('index', { title, })})app.listen(3000)
- 文件上传
busboy 模块是用来解析POST请求,node原生req中的文件流
const inspect = require('util').inspect const path = require('path')const fs = require('fs')const Busboy = require('busboy')// req 为node原生请求const busboy = new Busboy({ headers: req.headers })// ...// 监听文件解析事件busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { console.log(`File [${fieldname}]: filename: ${filename}`) // 文件保存到特定路径 file.pipe(fs.createWriteStream('./upload')) // 开始解析文件流 file.on('data', function(data) { console.log(`File [${fieldname}] got ${data.length} bytes`) }) // 解析文件结束 file.on('end', function() { console.log(`File [${fieldname}] Finished`) })})// 监听请求中的字段busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) { console.log(`Field [${fieldname}]: value: ${inspect(val)}`)})// 监听结束事件busboy.on('finish', function() { console.log('Done parsing form!') res.writeHead(303, { Connection: 'close', Location: '/' }) res.end()})req.pipe(busboy)
// user.sqlCREATE TABLE IF NOT EXISTS `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `nick` varchar(255) DEFAULT NULL, `detail_info` json DEFAULT NULL, `create_time` varchar(20) DEFAULT NULL, `modified_time` varchar(20) DEFAULT NULL, `level` int(11) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO `user` set email='1@example.com', password='123456';INSERT INTO `user` set email='2@example.com', password='123456';INSERT INTO `user` set email='3@example.com', password='123456';
- koa-jsonp
在项目复杂的业务场景,有时候需要在前端跨域获取数据,这时候提供数据的服务就需要提供跨域请求的接口,通常是使用JSONP的方式提供跨域接口
const Koa = require('koa')const jsonp = require('koa-jsonp')const app = new Koa()// 使用中间件app.use(jsonp())app.use( async ( ctx ) => { let returnData = { success: true, data: { text: 'this is a jsonp api', time: new Date().getTime(), } } // 直接输出JSON ctx.body = returnData})app.listen(3000, () => { console.log('[demo] jsonp is starting at port 3000')})
koa 中的设计模式