有的时候前端开发需要用到假数据,但是mock js 会显得不是很直观,而且自由度不是很好
这里采用了koa的服务器
最后工作流程为:在后端那里要来json文件,通过fs批量require进来,文件名就是变量名,注册到router上。
项目路径如下
appjs
var Koa = require('koa');
var bodyParser = require("koa-bodyparser")
var cors = require('koa2-cors');
var router = require('./router');
var app = new Koa();
app.use(cors())
.use(router.routes())
.use(router.allowedMethods())
.use(bodyParser())
.listen(3001)
routerjs
var Router = require('koa-router');
var router = new Router({
prefix: '/'
});
var fs = require('fs');
function Module(paths) {
var dirname = require("path").resolve(__dirname)
var modules = {};
var folder = dirname + paths
var files = fs.readdirSync(folder)
files.forEach(function(file) {
var filepath = folder + '/' + file;
let keys = file.split(".")[0]
modules[keys] = require(filepath)
})
return modules
}
let modules = Module("/json")
let routers = [
["table", modules.table],
['api-demo', modules.tree],
['api-demo', modules.login]
]
//全部是post
for (let i of routers) {
router.post(i[0], (ctx, next) => {
ctx.body = i[1]
})
}
function resultJS(data) {
return (ctx, next) => {
ctx.body = {
"success": true,
"message": "操作成功!",
"code": 0,
"result": data
}
}
}
function resultJSON(data) {
return (ctx, next) => {
ctx.body = data
}
}
router.get('api-demo', (ctx, next) => {
ctx.body = `gnvnv`
})
router.post('api-demo', resultJSON({ "success": true, "code": 200, "message": "操作成功", "data": { "dataList": [] } }))
module.exports = router
js文件是没有接口文档,自己模拟数据来使用的,基本上用不太到。
之后配置packagejson 整合到vue start里面
这里要填2个包
nodemon //server的热更新
concurrently //npm多开任务
"scripts": {
"dev": "vite",
"server": "nodemon ./_server/app.js",
"start": "concurrently \"npm run server\" \"npm run dev\" ",
"test": "vite build --mode test",
"prod": "vite build --mode prod",
"serve": "vite preview"
},