# 初始化package.json npm init # 安裝koa2 npm install koa
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')
因爲koa2是基於async/await操做中間件,目前node.js 7.x的harmony模式下才能使用,因此啓動的時的腳本以下:html
node index.js
router.js代碼以下:node
//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代碼以下:npm
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代碼以下:json
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代碼以下:api
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代碼以下:app
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代碼以下:koa
'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.jsasync