常用模块

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

koa 中的设计模式