直接上代码
//service.js
const Koa = require('koa') const KoaRouter = require('koa-router') const KoaBody = require('koa-body') KoaBody({ multipart: true }) const app = new Koa() const router = new KoaRouter() require('./test')(router) require('./chart')(router) app .use(KoaBody()) .use(router.routes()) .use(router.allowedMethods()) app.listen(8081, () => { console.log(`服务器启动成功,mock数据端口号:8081`) })
//package.json
{ "name": "Koa", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "mock": "nodemon ./server.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "koa": "^2.11.0", "koa-body": "^4.1.1", "koa-router": "^7.4.0", "nodemon": "^2.0.2" } }
//test.js
module.exports = function(router) { router.post('/test', ctx => { let result = [] for (let i = 0; i < 10; ++i) { let n = Math.ceil(Math.random() * 6) result.push({ value: n, name: i }) } ctx.body = { code: '200', msg: '操作成功', data: { pageNum: 1, total: 133, pageSize: 10, list: result } } }) }
//chart.js
var fs = require('fs'); var path = require('path'); module.exports = function(router) { // 图形 router.get('/chart', async ctx => { // 模版 let file = await fs.readFileSync(path.resolve(__dirname, 'chartConfig.json')) let data = JSON.parse(file) let result = { id: 0, name: 'hello world' } result.chartConfig = data ctx.body = { code: '200', msg: '操作成功', data: { taskDetailInfo: result } } }) }
//chartConfig.js
{ "scaleLimit": { "min": 1, "max": 20 }, "roam": true, "room": 1, "center": [ 115.97, 29.71 ], "series": [ { "name": "中国地图", "type": "map", "mapType": "china", "selectedMode": "single", "label": { "show": false, "color": "#fff", "fontSize": 12 }, "itemStyle": { "areaColor": "#ed45ed", "borderColor": "#FFFFFF" }, "emphasis": { "itemStyle": { "areaColor": "#f40" } }, "left": 0, "right": 0, "top": 0, "bottom": 0, "data": [] } ] }
调用:
axios.get('/chart').then(res => { console.log('响应::::', res) }); axios.post('/test').then(res => { console.log('响应::::', res) });
参考: https://www.npmjs.com/package/koa-body