4

一.hello koa

安装koa2

# 初始化package.json
npm init

# 安装koa2 
npm install koa

hello world 代码

新建index.js,代码如下:

const Koa = require('koa')
const app = new Koa()

app.use( async ( ctx ) => {
  ctx.body = 'hello koa2'
})

app.listen(3000)
console.log('[demo] start-quick is starting at port 3000')

启动demo

由于koa2是基于async/await操作中间件,目前node.js 7.x的harmony模式下才能使用,所以启动的时的脚本如下:

node index.js

272{NMV63(DOI%8HQR5)`UU.png

二.koa2 原生路由实现 和 get请求

//安装路由插件
npm install --save koa-router

index.js代码如下:

//index.js
const Koa = require('koa')  
const app = new Koa()  
  
const router = require('./routes/router')();  
app.use(router.routes()).use(router.allowedMethods())  
  
  
app.listen(3000, () => {  
  console.log('\[demo\] route-use-middleware is starting at port 3000')  
})

router.js代码如下:

const Router = require('koa-router')  
  
const home = require('./home')();  
const page = require('./page')();  
const api = require('./api')();  
  
module.exports \= () => {  
  // 装载所有子路由  
  let router = new Router()  
  router.use('/', home.routes(), home.allowedMethods())  
  router.use('/page', page.routes(), page.allowedMethods())  
  router.use('/api', api.routes(), api.allowedMethods())  
  return router;  
}

home.js代码如下:

const Router = require('koa-router')  
  
module.exports = () => {  
  
  let home = new Router()  
  // 子路由1  
  home.get('/', async ( ctx )=>{  
    let html = `  
 <ul> <li><a href="/page/helloworld">/page/helloworld</a></li> <li><a href="/page/404">/page/404</a></li><li><a href="/api/settings">/api/settings</a></li> </ul> `  ctx.body = html  
  })  
  
  return home;  
}

page.js代码如下:

const Router = require('koa-router')  
module.exports = () => {  
  let page = new Router()  
  page.get('/404', async ( ctx )=>{  
    ctx.body = '404 page!'  
  })  
  page.get('helloworld', async ( ctx )=>{  
    ctx.body = 'helloworld page!'  
  })  
  
  return page;  
}

api.js代码如下:

const Router = require('koa-router')  
  
const setController = require('../controllers/setController');  
  
  
module.exports = () => {  
  const api = new Router()      
  api.get('/settings',setController.getSettings)   
  
  return api;  
}

setController.js代码如下:

'use strict';  
  
const crypto = require('crypto');  
  
const AES_SECRET = '12e87e58475793133d5bb40c3ae76ca3';  
const AES_IV = 'udv93xitfeu6xg8q';  
  
const TAOBAO_SECRET_KEY = 'd34682618b6503641566ae83d971d35d';  
  
exports.getSettings = async (ctx, next) => {  
  
  let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(AES_SECRET), Buffer.from(AES_IV));  
  let encrypted = cipher.update(TAOBAO_SECRET_KEY);  
  
  encrypted = Buffer.concat([encrypted, cipher.final()]);  
  
  ctx.status = 200;  
  ctx.body = {  
    success: true,  
  msg: '',  
  settings: {  
      app_key: '27985254',  
  secret: encrypted.toString('hex'),  
  api:[  
        {  
          method: 'taobao.tbk.dg.material.optional',  
  adzone_id: 'mm_124732562_33032153_109589700162',  
  desc: '物料搜索'  
  },  
  {  
          method: 'taobao.tbk.dg.optimus.material',  
  adzone_id: 'mm_124732562_33032153_109589750184',  
  desc: '物料精选'  
  }  
      ]  
    }  
  };  
  return;  
}

输入指令 node index.js

ZIHR8YU_R[F7BUZLIT2~QIC.pngO59WSKF0[02}H935Q265PMW.png5%0)Z`{ZNJZ0[N1RUHC3LQJ.png

以上附链接:

学习 nodejs+mongodb+koa2 写接口(一) 环境布置
学习 nodejs+mongodb+koa2 写接口(二) koa2教程入门
学习 nodejs+mongodb+koa2 写接口(三) mongodb的增删改查
学习 nodejs+mongodb+koa2 写接口(四) 新建用户表,写用户的增删改查接口


Linda0821
62 声望4 粉丝