在前后端同步开发的过程中,前期后台接口出的没那么快,前端一般可以自己通过koa模拟后台接口—前提时与后台约定好数据格式。下面是如何用koa2模拟假数据接口的实现:
首先安装个koa脚手架
npm install koa-generator -g
koa生成一个server目录并安装依赖
koa2 server && cd server&& npm i
新建个假数据目录
mkdir mock
目录
DetailData的假数据长这样
module.exports = {
"msg": "成功",
"code": 200,
"data": {
"records": [{
"id": 149,
"alertName": "poseidon_httpClient_codeCountStat_count_total",
"buCode": "test",
"buName": "中间件",
"projectCode": "test-public",
"projectName": "中间件公共项目",
"resourceType": "java",
"resourceCode": "service_code_4431",
"resourceName": "mssp-web",
"alertStatus": 0,
"alertStatusName": "处理中",
"updateTime": "2022-03-23 14:57:57"
}],
"total": 66,
"size": 10,
"current": 1,
"orders": [
],
"optimizeCountSql": true,
"hitCount": false,
"countId": null,
"maxLimit": null,
"searchCount": true,
"pages": 7
},
"success": true,
"exception": null,
"attachment": null,
"errCode": 200
}
alarm.js里的长这样
const router = require('koa-router')()
let DetailData = require('../mock/historyDingTalkDetail')
router.get('/alert/history/dingTalk/detail', async (ctx, next) => {
ctx.append("Access-Control-Allow-Origin","*")
ctx.body = DetailData
})
module.exports = router
然后app.js里面的其它的不需要动,只是配置下路由就行
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(alarm.routes(), alarm.allowedMethods())
好了,接下来
npm run dev
// 或者
npm run start
// 都行,一个时修改热加载,一个要重启,看需求